问题
I have developed a java code that convert the following cURL to java code using URL and HttpUrlConnection. the curl is :
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\"}}\'
I have written this code but it always gives HTTP code 400 bad request. I couldn\'t find what is missing.
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());
}
回答1:
Your JSON is not correct. Instead of
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());
write
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());
So, the JSONObject.toString() should be called only once for the outer object.
Another thing (most probably not your problem, but I'd like to mention it):
To be sure not to run into encoding problems, you should specify the encoding, if it is not 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();
回答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:
You can use this code for connect and request using http and 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();
}
回答4:
the correct answer is good , but
OutputStreamWriter wr= new OutputStreamWriter(con.getOutputStream());
wr.write(parent.toString());
not work for me , instead of it , use :
byte[] outputBytes = rootJsonObject.getBytes("UTF-8");
OutputStream os = con.getOutputStream();
os.write(outputBytes);
回答5:
I had a similar issue, I was getting 400, Bad Request only with the PUT, where as POST request was perfectly fine.
Below code worked fine for POST but was giving BAD Request for PUT:
conn.setRequestProperty("Content-Type", "application/json");
os.writeBytes(json);
After making below changes worked fine for both POST and PUT
conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
os.write(json.getBytes("UTF-8"));
来源:https://stackoverflow.com/questions/21404252/post-request-send-json-data-java-httpurlconnection