1
我想從android應用程序使用HTTP發送到Herokuku服務器的JSON對象,然後得到它,但我不斷收到響應代碼:404,我不知道如果問題是從客戶端或服務器端,這裏是客戶端的HTTP連接:如何在java中使用從android發送到服務器的json對象?
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) {
}
}
這是服務器側的Heroku,我用java:
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";
});
}
}
謝謝,我應該聲明這樣的方法:post(「/ test」,(req,res),那是問題,現在我得到的響應代碼爲200。 – MuhammadNe