【问题标题】:POST request send JSON data Java HttpUrlConnectionPOST 请求发送 JSON 数据 Java HttpUrlConnection
【发布时间】:2014-01-28 11:23:08
【问题描述】:

我开发了一个 Java 代码,它使用 URL 和 HttpUrlConnection 将以下 cURL 转换为 Java 代码。 卷曲是:

curl -i 'http://url.com' -X POST -H "Content-Type: application/json" -H "Accept: application/json" -d '{"auth": { "passwordCredentials": {"username": "adm", "password": "pwd"},"tenantName":"adm"}}'

我已经编写了这段代码,但它总是给出 HTTP 代码 400 错误请求。我找不到丢失的东西。

String url="http://url.com";
URL object=new URL(url);

HttpURLConnection con = (HttpURLConnection) object.openConnection();
con.setDoOutput(true);
con.setDoInput(true);
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("Accept", "application/json");
con.setRequestMethod("POST");

JSONObject cred   = new JSONObject();
JSONObject auth   = new JSONObject();
JSONObject parent = new JSONObject();

cred.put("username","adm");
cred.put("password", "pwd");

auth.put("tenantName", "adm");
auth.put("passwordCredentials", cred.toString());

parent.put("auth", auth.toString());

OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream());
wr.write(parent.toString());
wr.flush();

//display what returns the POST request

StringBuilder sb = new StringBuilder();  
int HttpResult = con.getResponseCode(); 
if (HttpResult == HttpURLConnection.HTTP_OK) {
    BufferedReader br = new BufferedReader(
            new InputStreamReader(con.getInputStream(), "utf-8"));
    String line = null;  
    while ((line = br.readLine()) != null) {  
        sb.append(line + "\n");  
    }
    br.close();
    System.out.println("" + sb.toString());  
} else {
    System.out.println(con.getResponseMessage());  
}  

【问题讨论】:

  • Java 冗长的漂亮插图。

标签: java json post curl httpurlconnection


【解决方案1】:

您的 JSON 不正确。而不是

JSONObject cred = new JSONObject();
JSONObject auth=new JSONObject();
JSONObject parent=new JSONObject();
cred.put("username","adm");
cred.put("password", "pwd");
auth.put("tenantName", "adm");
auth.put("passwordCredentials", cred.toString()); // <-- toString()
parent.put("auth", auth.toString());              // <-- toString()

OutputStreamWriter wr= new OutputStreamWriter(con.getOutputStream());
wr.write(parent.toString());

JSONObject cred = new JSONObject();
JSONObject auth=new JSONObject();
JSONObject parent=new JSONObject();
cred.put("username","adm");
cred.put("password", "pwd");
auth.put("tenantName", "adm");
auth.put("passwordCredentials", cred);
parent.put("auth", auth);

OutputStreamWriter wr= new OutputStreamWriter(con.getOutputStream());
wr.write(parent.toString());

因此,JSONObject.toString() 应该只为外部对象调用一次。

另一件事(很可能不是你的问题,但我想提一下):

为确保不遇到编码问题,你应该指定编码,如果不是UTF-8:

con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
con.setRequestProperty("Accept", "application/json");

// ...

OutputStream os = con.getOutputStream();
os.write(parent.toString().getBytes("UTF-8"));
os.close();

【讨论】:

  • 在我的情况下,设置请求属性的内容类型至关重要:con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
  • 没有什么对我有用。我正在发送输入,但在 API 端我收到的是空白。
【解决方案2】:
private JSONObject uploadToServer() throws IOException, JSONException {
            String query = "https://example.com";
            String json = "{\"key\":1}";

            URL url = new URL(query);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5000);
            conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setRequestMethod("POST");

            OutputStream os = conn.getOutputStream();
            os.write(json.getBytes("UTF-8"));
            os.close();

            // read the response
            InputStream in = new BufferedInputStream(conn.getInputStream());
            String result = org.apache.commons.io.IOUtils.toString(in, "UTF-8");
            JSONObject jsonObject = new JSONObject(result);


            in.close();
            conn.disconnect();

            return jsonObject;
    }

【讨论】:

    【解决方案3】:

    您可以使用此代码使用 http 和 json 进行连接和请求

    try {
             
            URL url = new URL("https://www.googleapis.com/youtube/v3/playlistItems?part=snippet"
                    + "&key="+key
                    + "&access_token=" + access_token);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json");
     
            String input = "{ \"snippet\": {\"playlistId\": \"WL\",\"resourceId\": {\"videoId\": \""+videoId+"\",\"kind\": \"youtube#video\"},\"position\": 0}}";
     
            OutputStream os = conn.getOutputStream();
            os.write(input.getBytes());
            os.flush();
     
            if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
                throw new RuntimeException("Failed : HTTP error code : "
                    + conn.getResponseCode());
            }
     
            BufferedReader br = new BufferedReader(new InputStreamReader(
                    (conn.getInputStream())));
     
            String output;
            System.out.println("Output from Server .... \n");
            while ((output = br.readLine()) != null) {
                System.out.println(output);
            }
     
            conn.disconnect();
     
          } catch (MalformedURLException e) {
     
            e.printStackTrace();
     
          } catch (IOException e) {
     
            e.printStackTrace();
     
         }
    

    【讨论】:

      【解决方案4】:

      正确答案很好,但是

      OutputStreamWriter wr= new OutputStreamWriter(con.getOutputStream());
      wr.write(parent.toString());
      

      不适合我,而不是它,使用

      byte[] outputBytes = rootJsonObject.getBytes("UTF-8");
      OutputStream os = con.getOutputStream();
      os.write(outputBytes);
      

      【讨论】:

      • 它对你不起作用,因为你忘记关闭 OutputStreamWriter
      【解决方案5】:

      我有一个类似的问题,我得到了 400,只有 PUT 的错误请求,而 POST 请求完全没问题。

      下面的代码在 POST 上运行良好,但对 PUT 发出了 BAD Request:

      conn.setRequestProperty("Content-Type", "application/json");
      os.writeBytes(json);
      

      进行以下更改后,POST 和 PUT 都可以正常工作

      conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
      os.write(json.getBytes("UTF-8"));
      

      【讨论】:

        【解决方案6】:

        这是完整的代码和解决方案

        PostJSONWithHttpURLConnection.java 类

        import android.util.Log;
        import org.json.JSONException;
        import org.json.JSONObject;
        import java.io.BufferedInputStream;
        import java.io.BufferedReader;
        import java.io.IOException;
        import java.io.InputStream;
        import java.io.InputStreamReader;
        import java.io.OutputStream;
        import java.net.HttpURLConnection;
        import java.net.URL;
        
        public class PostJSONWithHttpURLConnection {
            String charset = "UTF-8";
            HttpURLConnection con;
            URL urlObj;
            JSONObject jObj = null;
            StringBuilder result;
        
            public JSONObject makeHttpRequest(String url,
                                              String paramsJSON) {
                try {
                    urlObj = new URL(url);
                    con = (HttpURLConnection) urlObj.openConnection();
                    con.setRequestMethod("POST");
                    con.setRequestProperty("Content-Type", "application/json; utf-8");
                    con.setRequestProperty("Accept", "application/json");
        
                    con.setDoOutput(true);
                    con.setReadTimeout(60000);
                    con.setConnectTimeout(60000);
        
                    try (OutputStream os = con.getOutputStream()) {
                        byte[] input = paramsJSON.getBytes(charset);
                        os.write(input, 0, input.length);
                    }
        
                    int code = con.getResponseCode();
                    Log.d("HTTP CODE", String.valueOf(code));
                } catch (IOException e) {
                    e.printStackTrace();
                }
        
                try {
                    //Receive the response from the server
                    InputStream in = new BufferedInputStream(con.getInputStream());
                    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                    result = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        result.append(line);
                    }
        
                    Log.d("JSON Parser", "result: " + result.toString());
        
                } catch (IOException e) {
                    e.printStackTrace();
                }
        
                con.disconnect();
        
                // try parse the string to a JSON object
                try {
                    jObj = new JSONObject(result.toString());
                } catch (JSONException e) {
                    Log.e("JSON Parser", "Error parsing data " + e.toString());
                }
        
                return jObj;
            }
        }
        

        doInBackground(String... strArr) 上代码的使用

        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        String writeValueAsString = objectMapper.writeValueAsString(jSONObject);   
        PostJSONWithHttpURLConnection jsonPOST = new PostJSONWithHttpURLConnection();
        JSONObject json = jsonPOST.makeHttpRequest(SERVER_ADDRESS + "YOUR_API", writeValueAsString);
        

        jSONObject 是一个 Json Like:

        {
        "Password":"PASSWORD",
        "FullName":"Full Name",
        "Username":"USER_NAME"
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-12-06
          • 2020-01-11
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-07-07
          相关资源
          最近更新 更多