2014-01-28 8 views
75

Ich habe einen Java-Code entwickelt senden, die die folgenden cURL zu Java-Code mit URL und HttpURLConnection konvertieren. die Locke ist:POST-Anfrage json Daten 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"}}' 

ich diesen Code geschrieben haben, aber es gibt immer HTTP-Code 400 schlecht Anfrage. Ich konnte nicht finden, was fehlt.

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

Schöne Illustration für java Ausführlichkeit PUT. – yurin

Antwort

145

Ihr JSON ist nicht korrekt. Statt

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

Schreib

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

Also, die JSONObject.toString() sollte nur einmal für das äußere Objekt aufgerufen werden.

Eine andere Sache (die meisten wahrscheinlich nicht Ihr Problem, aber ich möchte es ganz zu schweigen):

sicher zu sein, nicht in Codierung Probleme zu laufen, sollten Sie die Codierung angeben, wenn es nicht UTF-8 ist:

con.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); 

// ... 

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

In meinem Fall Einstellung der Content-Type-Antrag Eigenschaft war entscheidend: 'con.setRequestProperty ("Content-Type", "application/json; charset = UTF-8");' – Morey

13

können Sie diesen Code verwenden für den Anschluss und Anforderung mit http und 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(); 

    } 

, wenn Sie einen Fehler fügen Sie diese sehen, aber dies ist keine gute Arbeit geleistet.

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

die richtige Antwort ist gut, aber

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

nicht für mich arbeiten, statt es, Verwendung:

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

Ohhh danke !!!! Das machte meinen Tag !!! – 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

Ich hatte ein ähnliches Problem, Ich bekam 400, schlechte Anfrage nur mit dem PUT, wo als POST-Anfrage völlig in Ordnung war.

Below Code arbeitete für POST in Ordnung, aber war schlecht Antrag auf PUT geben:

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

Nach unten Änderungen arbeitete für beide POST fein und

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