2016-10-10 57 views
0

我試圖JSON對象發送到我的web服務器和android應用。我找到的每個例子都使用了已經被android 6刪除的HttpClient。請有人給我一個HttpURLConnection方法的例子。如何發送一個JSON對象與HttpURLConnection的Android中

+0

爲什麼不直接使用Retrofit HTTP客戶端並節省所有的麻煩? –

+0

注意:不是Android問題,但存在更好的庫。 Volley和OkHttp是最流行的 –

+1

而另一個。 http://stackoverflow.com/questions/21404252/post-request-send-json-data-java-httpurlconnection –

回答

0

這裏是你如何使用HttpURLConnection的一個例子:

JSONObject json = getJSONData(); 
String targetURL = getTargetURL(); 

HttpURLConnection con = (HttpURLConnection)new URL(targetURL).openConnection(); 
con.setDoOutput(true); 
con.setRequestMethod("POST"); 
con.setRequestProperty("Content-Type", "application/json"); 
con.setChunkedStreamingMode(0); 

StringBuilder output = new StringBuilder(); 
output.append("data="); 
output.append(URLEncoder.encode(data.get(json.toString()), "UTF-8")); 

BufferedOutputStream stream = new BufferedOutputStream(con.getOutputStream()); 
stream.write(output.toString().getBytes()); 
out.flush(); 

con.connect(); 

Exception result = null; 
int responseCode = con.getResponseCode(); 
switch(responseCode) { 
    case 200: //all ok 
     break; 
    case 401: 
    case 403: 
     // authorized 
     break; 
    default: 
     //whatever else... 
     String httpResponse = con.getResponseMessage(); 
     BufferedReader br = new BufferedReader(new InputStreamReader(con.getErrorStream())); 
     String line; 
     try { 
      while ((line = br.readLine()) != null) { 
       Log.d("error", " " + line); 
      } 
     } 
     catch(Exception ex) { 
      //nothing to do here 
     } 

     break; 
} 

con.disconnect(); 

這就是說,你應該認真考慮使用現有的庫,這將隱藏了大部分的這些來自你。

+0

我已閱讀離子與凌空抽射,但不知道該使用或學習前進。你能請教我一個人學習未來嗎? – master

相關問題