【问题标题】:Can't send a correct POST request in Java (Android Studio)无法在 Java (Android Studio) 中发送正确的 POST 请求
【发布时间】:2016-05-30 11:59:44
【问题描述】:

我正在创建一个用于提问/回答问题的应用。 我在提问时遇到 POST 请求问题。

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

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

【问题讨论】:

  • Hashmap 中的信息未发送到服务器(或者可能已发送,但未正确创建请求)
  • 您是否尝试使用 Volley 发送它?
  • 如果你去link你可以看到,前3个请求是从终端发送的,其他请求是从Java发送的
  • @ValentinaPakhomova 如果您的内容类型是 app json,我猜它不会接受您的密钥对值作为请求!
  • 你试过改造吗?

标签: java android android-studio http-post


【解决方案1】:

像这样试试..

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

【讨论】:

    【解决方案2】:

    我刚刚尝试创建一个用户并且它有效。你可以刷新你分享的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){
    
            }
    

    更新

    顺便说一句,我使用了来自this链接的json jar

    【讨论】:

    • 非常感谢,成功了!!顺便说一句,android 已经移除了对 Apache HTTP 客户端的支持
    • @ValentinaPakhomova 很高兴!这有帮助!
    【解决方案3】:

    试试这个希望它会工作

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

    【讨论】:

      【解决方案4】:

      基本上,您的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 sn-p http://your-app-name.herokuapp.com/contactshttps://safe-citadel-91138.herokuapp.com/questions 中的不同,也许您也在与错误的端点通信?

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

      更新

      • 为 JSON 映射添加了指向 gson 的链接
      • 更新了代码 sn-p 以使用 JSONObject 进行 JSON 映射

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-07-03
        • 2020-12-29
        • 2015-12-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多