HttpURLconnection使用POST方式提交JSON資料給伺服器
阿新 • • 發佈:2018-11-07
HttpURLconnection使用POST方式提交JSON資料給伺服器
版權宣告:本文為博主原創文章,未經博主允許不得轉載。 https://blog.csdn.net/caidi1988314/article/details/72916165
HttpURLconnection使用POST方式提交JSON資料給伺服器
最原始的味道,使用HttpURLconnection提交JSON資料給後臺伺服器。此處留下標記。
- 將javabean物件轉換成Json字串。
- 通過HttpUrlconnection提交資料。
- getRequestCode返回415
1.javabean轉換成JSON字串工具類。這裡使用Gson解析器,請各位自行新增依賴包。
//將JSON字串轉換成javabean public static <T> T parsr(String json ,Class<T> tClass){ //判讀字串是否為空 if(TextUtils.isEmpty(json)){ return null; } if(gson==null){ gson = new Gson(); } return gson.fromJson(json,tClass); } //將javabean轉換成JSON字串 public static String converJavaBeanToJson(Object obj){ if(obj == null){ return ""; } if(gson == null){ gson = new Gson(); } String beanstr = gson.toJson(obj); if(!TextUtils.isEmpty(beanstr)){ return beanstr; } return ""; }
- HttpUrlconnection部分
//傳送JSON字串 如果成功則返回成功標識。 public static String doJsonPost(String urlPath, String Json) { // HttpClient 6.0被拋棄了 String result = ""; BufferedReader reader = null; try { URL url = new URL(urlPath); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setDoInput(true); conn.setUseCaches(false); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("Charset", "UTF-8"); // 設定檔案型別: conn.setRequestProperty("Content-Type","application/json; charset=UTF-8"); // 設定接收型別否則返回415錯誤 //conn.setRequestProperty("accept","*/*")此處為暴力方法設定接受所有型別,以此來防範返回415; conn.setRequestProperty("accept","application/json"); // 往伺服器裡面傳送資料 if (Json != null && !TextUtils.isEmpty(Json)) { byte[] writebytes = Json.getBytes(); // 設定檔案長度 conn.setRequestProperty("Content-Length", String.valueOf(writebytes.length)); OutputStream outwritestream = conn.getOutputStream(); outwritestream.write(Json.getBytes()); outwritestream.flush(); outwritestream.close(); Log.d("hlhupload", "doJsonPost: conn"+conn.getResponseCode()); } if (conn.getResponseCode() == 200) { reader = new BufferedReader( new InputStreamReader(conn.getInputStream())); result = reader.readLine(); } } catch (Exception e) { e.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } } return result; }