如何在java中使用从android发送到服务器的json对象?

时间:2016-02-14 16:35:24

标签: java android json heroku

我正在尝试使用HTTP帖子从Android应用程序传递JSON对象到heroku服务器然后取回它,但我一直得到响应代码:404,我不知道问题是来自客户端还是服务器端,这是客户端HTTP连接:

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";
    });
  }
}

1 个答案:

答案 0 :(得分:1)

客户端向/test发送POST请求,但服务器仅为该路由定义GET处理程序。 (Imho服务器应该以不允许的405方法响应,但也许这就是Spark响应的方式)。

因此,请尝试为POST请求定义处理程序。