2017-05-03 43 views
0

好吧,我已經嘗試了過去24個關於如何做到這一點的代碼示例,但我無法獲得任何工作。在Android應用中使用JSON正文發送HTTP請求

我只是想通過JSON機構到URL。 每一件事情用cURLBASH工作的權利,我甚至想我們

Runtime.getRuntime().exec("curl....."); 

但即使不通過JSON身體,其實我已經成功地與Runtime.getRuntime().exec(str)和其他幾個發送http請求方式,但他們通過了JSON機構。

我會很感激任何幫助。

回答

0

您應該使用改造。 有很多樣品herehere's同樣的問題

0

如果你想編寫自己的方法: 這是一個。

private JsonObject postJsonObject(JsonObject jsonObject) { 
     JsonObject nullresult = new JsonObject(); 
     nullresult.addProperty("success",-1); 
     try { 
      String data = jsonObject.toString(); 
      URL object = new URL(url); \\MENTION YOUR URL HERE 

      HttpURLConnection httpURLConnection = (HttpURLConnection) object.openConnection(); 
      httpURLConnection.setDoOutput(true); 
      httpURLConnection.setDoInput(true); 
      httpURLConnection.setRequestProperty("Content-Type", "application/json"); 
      httpURLConnection.setRequestProperty("Accept", "application/json"); 
      httpURLConnection.setRequestMethod("POST"); 

      httpURLConnection.setConnectTimeout(8000); 
      httpURLConnection.setReadTimeout(8000); 

      OutputStreamWriter wr = new OutputStreamWriter(httpURLConnection.getOutputStream()); 
      wr.write(data); 
      wr.flush(); 

      StringBuilder sb = new StringBuilder(); 
      int HttpResult = httpURLConnection.getResponseCode(); 
      if (HttpResult == HttpURLConnection.HTTP_OK) { 
       BufferedReader br = new BufferedReader(
         new InputStreamReader(httpURLConnection.getInputStream(), "utf-8")); 
       String line; 
       while ((line = br.readLine()) != null) { 
        sb.append(line).append("\n"); 
       } 
       br.close(); 
      } 
      JsonObject result = new JsonParser().parse(sb.toString()).getAsJsonObject(); 

      if(result !=null) 
       return result; 
      else 
       return nullresult; 
     } catch (ProtocolException e) { 
      e.printStackTrace(); 
     } catch (MalformedJsonException e){ 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
     return nullresult; 
    } 

您還可以使用庫如Ion。 鏈接:https://github.com/koush/ion

這是很容易理解android的網絡庫。他們有可以幫助你的例子。