POST请求发送json数据java HttpUrlConnection

时间:2014-01-28 11:23:08

标签: java json post curl httpurlconnection

我开发了一个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());  
}  

5 个答案:

答案 0 :(得分:162)

您的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();

答案 1 :(得分:32)

db.myCollection.update({}, {$unset : {"addedpartners.1" : 1 }}) 
db.myCollection.update({}, {$pull : {"addedpartners" : null}})

答案 2 :(得分:14)

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

进行请求
try {

        URL url = new URL("https://www.googleapis.com/youtube/v3/playlistItems?part=snippet"
                + "&key=AIzaSyAhONZJpMCBqCfQjFUj21cR2klf6JWbVSo"
                + "&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();

     }

答案 3 :(得分:5)

正确答案是好的,

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

不适合我,而不是使用

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

答案 4 :(得分:1)

我有一个类似的问题,我得到400,只有PUT的错误请求,其中POST请求完全正常。

下面的代码适用于POST,但是给了PUT请求PUT:

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