2014-01-28 8 views
75

URL 및 HttpUrlConnection을 사용하여 다음 cURL을 Java 코드로 변환하는 Java 코드를 개발했습니다. 컬이 : 나는이 코드를 작성했습니다POST 요청 json 데이터 보내기 java HttpUrlConnection

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()); 
} 
+2

좋은 그림을 넣습니다. – yurin

답변

145

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

// ... 

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

제 경우에는 요청 속성의 content-type을 설정하는 것이 중요했습니다. 'con.setRequestProperty ("Content-Type", "application/json; charset = UTF-8"),' – Morey

13

당신은 당신이 오류가이 추가를 참조하면 연결 요청은 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(); 

    } 

를 사용하여이 코드를 사용할 수 있지만, 이것은 좋은 일이 아니다.

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

정답은 사용, 하지만

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

없는 대신에, 저 위해 일 좋은 비슷한 문제, POST 요청이 완벽하게 괜찮 았던 PUT에서만 400이라는 잘못된 요청을 받았습니다. 코드 아래

는 POST를 위해 잘 작동하지만, PUT에 대한 잘못된 요청을주고 있었다 :

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

변경 아래 한 후에 POST 모두 잘 작동하고 자바 상세 대한

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

Ohhh thank you !!!! 이것은 나의 날을 만들었다! !! – Imeksbank

21
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; 
    } 
0

내가 가진 :

if (Build.VERSION.SDK_INT >= 9) { 
     StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); 
     StrictMode.setThreadPolicy(policy); 
    }