POST 请求发送 json 数据 java HttpUrlConnection
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21404252/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
POST request send json data java HttpUrlConnection
提问by user3244172
I have developed a java code that convert the following cURL to java code using URL and HttpUrlConnection. the curl is :
我开发了一个 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"}}'
I have written this code but it always gives HTTP code 400 bad request. I couldn't find what is missing.
我写了这段代码,但它总是给出 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());
}
回答by hgoebl
Your JSON is not correct. Instead of
您的 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());
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.
因此,对于外部对象, JSONObject.toString() 应该只调用一次。
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
:
为了确保不会遇到编码问题,您应该指定编码,如果不是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();
回答by Burak Durmu?
You can use this code for connect and request using http and json
您可以使用此代码使用 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();
}
回答by Adnan Abdollah Zaki
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);
回答by NickUnuchek
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;
}
回答by vkumar22
I had a similar issue, I was getting 400, Bad Request only with the PUT, where as POST request was perfectly fine.
我有一个类似的问题,我得到了 400,只有 PUT 的错误请求,而 POST 请求完全没问题。
Below code worked fine for POST but was giving BAD Request for PUT:
下面的代码对 POST 工作正常,但对 PUT 给出了 BAD 请求:
conn.setRequestProperty("Content-Type", "application/json");
os.writeBytes(json);
After making below changes worked fine for both POST and PUT
进行以下更改后,POST 和 PUT 都可以正常工作
conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
os.write(json.getBytes("UTF-8"));