반응형
POST 요청 json 데이터 보내기 java HttpUrlConnection
URL 및 HttpUrlConnection을 사용하여 다음 cURL을 Java 코드로 변환하는 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());
}
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();
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;
}
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();
}
정답은, 좋은 있지만,
OutputStreamWriter wr= new OutputStreamWriter(con.getOutputStream());
wr.write(parent.toString());
나를 위해 작동하지 않고 대신 다음을 사용하십시오 .
byte[] outputBytes = rootJsonObject.getBytes("UTF-8");
OutputStream os = con.getOutputStream();
os.write(outputBytes);
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"));
참고URL : https://stackoverflow.com/questions/21404252/post-request-send-json-data-java-httpurlconnection
반응형
'Programming' 카테고리의 다른 글
504 게이트웨이 시간 초과를 유발하는 Nginx 역방향 프록시 (0) | 2020.08.24 |
---|---|
TextInputEditText에 초점을 맞출 때 Android 8.0 Oreo 충돌 (0) | 2020.08.24 |
iPhone 6 / iOS 8로 NFC 태그 읽기 (0) | 2020.08.24 |
JavaScript for 루프로 json을 만드는 방법은 무엇입니까? (0) | 2020.08.24 |
키 누르기 이벤트 후 jquery .val ()을 어떻게 얻을 수 있습니까? (0) | 2020.08.24 |