无法在 Java (Android Studio) 中发送正确的 POST 请求

Can't send a correct POST request in Java (Android Studio)

我正在为 asking/answering 个问题创建一个应用程序。 POST request 当我提问时遇到问题

我试过在终端中使用类似的东西

curl -H "Content-Type: application/json" -d '{"firstName":"Chris", "lastName": "Chang", "email": "support@mlab.com"}' http://your-app-name.herokuapp.com/contacts

效果很好。

但是当我尝试在 AndroidStudio 中发送 POST 请求时,我的参数(例如姓名、姓氏、电子邮件等)不会发送。 我尝试使用 https://github.com/kevinsawicki/http-request。请求已发送(我知道是因为它显示了请求的日期)但没有任何参数。

我的代码应该更改哪些内容才能正常工作?

Map<String, String> data = new HashMap<String, String>();
data.put("firstName", "Gena");
data.put("lastName", "Bukin");
if (HttpRequest.post("https://safe-citadel-91138.herokuapp.com/questions").form(data).created())
System.out.println("User was created");

基本上,您的 curl 请求会在请求正文中以 JSON 格式发送用户数据。您的 Java 代码尝试将请求中的数据作为表单数据发送,这是不同的并且可能不被服务器接受。

您可能需要更改代码以使用 HttpRequest.send(...) 方法而不是 form:

JSONObject json = new JSONObject();
json.put("firstName", "Gena");
json.put("lastName", "Bukin");
json.put("email", "support@mlab.com");

HttpRequest
    .post("https://safe-citadel-91138.herokuapp.com/questions")
    .contentType("application/json")
    .send(json.toString());

此外,在 curl 调用中,您使用的访问权限 url 与 Java 代码段 http://your-app-name.herokuapp.com/contactshttps://safe-citadel-91138.herokuapp.com/questions 中的不同,也许您正在与端点也错误?

您可能想看看一些 Java 到 JSON 映射库,例如 gson,以便将您的 Java 对象转换为正确的 JSON 或使用 Android 的 JSONObject class.

更新

  • 已将 link 添加到 gson 以进行 JSON 映射
  • 已更新代码段以将 JSONObject 用于 JSON 映射

尝试这个希望它会工作

public JSONObject getJSONFromUrl(String url_, JSONObject jsonObject) {

    try {
        URLConnection urlConn;
        DataOutputStream printout;

        URL url = new URL(url_);
        urlConn = url.openConnection();
        urlConn.setDoInput(true);
        urlConn.setDoOutput(true);
        urlConn.setConnectTimeout(30000);
        urlConn.setReadTimeout(30000);
        urlConn.setUseCaches(false);
        urlConn.setRequestProperty("Content-Type", "application/json");
        urlConn.setRequestProperty("Accept", "application/json");

        urlConn.setRequestProperty("Authorization", "token"); // If Applicable 
        urlConn.connect();
        printout = new DataOutputStream(urlConn.getOutputStream());
        printout.writeBytes(jsonObject.toString());
        printout.flush();
        BufferedReader reader = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));

        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        printout.close();
        reader.close();
        json = sb.toString();
    } catch (SocketException e) {
        e.printStackTrace();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    Applog.e("response", jObj + "");
    return jObj;

}

这样试试..

Map<String, Object> params = new LinkedHashMap<>();
params.put("firstName", "Gena");
params.put("lastName", "Bukin");


JSONObject jsonObject = POST("https://safe-citadel-91138.herokuapp.com/questions", params);
    /**
         * Method allows to HTTP POST request to the server to send data to a specified resource
         * @param serverURL URL of the API to be requested
         * @param params parameter that are to be send in the "body" of the request Ex: parameter=value&amp;also=another
         * returns response as a JSON object
         */
        public JSONObject POST(String serverURL, Map<String, Object> params) {
            JSONObject jsonObject = null;
            try {
                URL url = new URL(serverURL);

                Log.e(TAG, params.toString());
                StringBuilder postData = new StringBuilder();

                for (Map.Entry<String, Object> param : params.entrySet()) {
                    if (postData.length() != 0) postData.append('&');
                    postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
                    postData.append('=');
                    postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
                }
                Log.e("POST", serverURL + ":" + params.toString());
                byte[] postDataBytes = postData.toString().getBytes("UTF-8");
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setRequestProperty("Content-Type", "application/json");
                connection.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
                connection.setRequestMethod("POST");
                connection.setConnectTimeout(5000);
                connection.setUseCaches(false);
                connection.setDoOutput(true);
                connection.getOutputStream().write(postDataBytes);
                connection.connect();

                int statusCode = connection.getResponseCode();
                if (statusCode == 200) {
                    sb = new StringBuilder();
                    reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                    String line;
                    while ((line = reader.readLine()) != null) {
                        sb.append(line + "\n");
                    }
                }
                jsonObject = new JSONObject(sb.toString());
            } catch (Exception e) {
                //e.printStackTrace();
            }
            return jsonObject;
        }

我刚刚尝试创建一个用户并且成功了。您可以刷新您分享的 link 查看创建的用户。

这是我试过的

String endPoint= "https://safe-citadel-91138.herokuapp.com/questions";
        try {

            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost post = new HttpPost(endPoint);
            post.addHeader("Content-Type", "application/json");
            JSONObject obj = new JSONObject();

            obj.put("firstName", "TESTF");
            obj.put("lastName", "TESTL");
            obj.put("email", "support@mlab.com");

            StringEntity entity = new StringEntity(obj.toString()); 
            post.setEntity(entity);
            HttpResponse response = httpClient.execute(post);
}catch (Exception e){

        }

更新

顺便说一句,我使用了 json 来自 this link

的 jar