2017-02-19 4 views
0

Ich versuche, eine JSON zu schreiben, die kann nicht in einer Antwort von POST JSON in HttpURLConnection bekommen android

{ 
    "latLong":"50.1109,8.6821 - latLong", 
    "currencyCode":"EUR", 
    "locale":"en-GB", 
    "budget":"" 
} 

wie

aussieht, wenn ich dies tun mit Postman, ich die Antwort bin bekommen, was ich brauche. Aber in Android Studio kompiliert es nicht und ich bekomme eine leere Zeichenfolge zurückgegeben. Meine Funktion sieht so aus.

protected Void doInBackground(Void... params) { 

     URL url = null; 
     StringBuffer sb = new StringBuffer(); 

     try { 
      url = new URL("http://192.168.2.101:12345/services/test"); 
     } catch (MalformedURLException e) { 
      e.printStackTrace(); 
     } 
     HttpURLConnection con = null; 
     try { 
      con = (HttpURLConnection) url.openConnection(); 
      con.setRequestMethod("POST"); 
      con.setDoOutput(true); 
      con.setRequestProperty("Content-Type","application/json"); 
      DataOutputStream printout = new DataOutputStream(con.getOutputStream()); 

      String Json_String = "{\n" + 
        " \"latLong\":\"50.1109,8.6821 - latLong\",\n" + 
        " \"currencyCode\":\"EUR\",\n" + 
        " \"locale\":\"en-GB\",\n" + 
        " \"budget\":\"\"\n" + 
        "}"; 

      InputStream in = new BufferedInputStream(con.getInputStream()); 
      BufferedReader br = new BufferedReader(new InputStreamReader(in)); 
      String inputLine = ""; 
      while ((inputLine = br.readLine()) != null) { 
       sb.append(inputLine); 
      } 
      result = sb.toString(); 

      printout.flush(); 
      printout.close(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 

     try { 
      responseMsg = con.getResponseMessage(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
     try { 
      response = con.getResponseCode(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
     return null; 
    } 
} 

Antwort

0

Verwenden Output statt Dataoutputstream und con.setDoOutput(true) kommen sollten vor der Veröffentlichung.

Grundsätzlich gilt:

con = (HttpURLConnection) url.openConnection(); 
    con.setDoOutput(true); 
    con.setRequestMethod("POST"); 

    OutputStreamWriter writer = new OutputStreamWriter(
      con.getOutputStream()); 
    String Json_String = "{\n" + 
      " \"latLong\":\"50.1109,8.6821 - latLong\",\n" + 
      " \"currencyCode\":\"EUR\",\n" + 
      " \"locale\":\"en-GB\",\n" + 
      " \"budget\":\"\"\n" + 
      "}"; 

    writer.write(Json_String); 
    writer.close(); 

    if (con.getResponseCode() == HttpURLConnection.HTTP_OK) { 
     // OK 
     InputStream in = new BufferedInputStream(con.getInputStream()); 
     BufferedReader br = new BufferedReader(new InputStreamReader(in)); 
     String inputLine = ""; 
     while ((inputLine = br.readLine()) != null) { 
      sb.append(inputLine); 
     } 
     string result = result = sb.toString(); 
Verwandte Themen