如何使用java中从android发送到服务器的json对象?
我正在尝试使用HTTP post将android应用程序中的JSON对象传递到heroku服务器,然后将其取回,但我一直得到响应代码:404,我不知道问题是来自客户端还是服务器端,以下是客户端HTTP连接:如何使用java中从android发送到服务器的json对象?,java,android,json,heroku,Java,Android,Json,Heroku,我正在尝试使用HTTP post将android应用程序中的JSON对象传递到heroku服务器,然后将其取回,但我一直得到响应代码:404,我不知道问题是来自客户端还是服务器端,以下是客户端HTTP连接: class JsonAsyncTask extends AsyncTask<Void, Void, String> { private final String USER_AGENT = "Mozilla/5.0"; protected void onPreE
class JsonAsyncTask extends AsyncTask<Void, Void, String> {
private final String USER_AGENT = "Mozilla/5.0";
protected void onPreExecute() {
}
@Override
protected String doInBackground(Void... params) {
try {
String url = "https://jce-blb.herokuapp.com/test";
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
//add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("Accept", "application/json");
con.setRequestProperty("Content-type", "application/json");
JSONObject jsonObject = new JSONObject();
jsonObject.put("name", "Android");
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(jsonObject.toString());
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
System.out.println(response.toString());
} catch (Exception e) {
}
return null;
}
protected void onPostExecute(String content) {
}
}
客户端向
/test
发送POST请求,但服务器仅为该路由定义GET处理程序。(Imho服务器不允许使用405方法响应,但Spark可能就是这样响应的)
因此,请尝试为POST请求定义一个处理程序。谢谢,我应该这样声明方法:POST(“/test)”,(req,res),这就是问题所在,现在我得到了响应代码200。
import java.sql.*;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.Map;
import java.net.URI;
import java.net.URISyntaxException;
import static spark.Spark.*;
import spark.template.freemarker.FreeMarkerEngine;
import spark.ModelAndView;
import static spark.Spark.get;
import com.heroku.sdk.jdbc.DatabaseUrl;
public class Main {
public static void main(String[] args) {
port(Integer.valueOf(System.getenv("PORT")));
staticFileLocation("/public");
get("/test", (req,res) -> {
return "im back";
});
}
}