標籤:style blog http color os io 使用 strong ar
介面文檔:
換頭像介面 user/change_avatar發送資料HTTP Post body(一共2對KEY-VALUE):json={"uid":"1","sid":"0123456789ABCDEF0123456789ABCDEF","ver":"1","request":{}}file=圖片二進位檔案資料返回資料{"ret":0,"response":{ "status":1, "url":"http://192.168.1.200:8088/thumb.php?src=984340199_1667541218_1540991412.jpg&t=a&w=112&h=112" }}
遇到的問題:
首先在封裝二進位請求體參數時,傳遞參數不足,導致伺服器端不識別POST請求。
HttpUtils http = new HttpUtils(); RequestParams params = new RequestParams(); params.addBodyParameter("json", json); for (int i = 0; i < files.size(); i++) { if (files.get(i) != null) { try { params.addBodyParameter("file"+i, new FileInputStream( files.get(i)), files.get(i).length(), files.get(i) .getName(), "application/octet-stream"); } catch (FileNotFoundException e) { e.printStackTrace(); } } }
params.addBodyParameter(key, stream, length, fileName, mimeType);
然後在發送POST請求時,使用的是非同步方法呼叫,導致不能返回伺服器返回的值。
String s = null; try { // 同步方法,擷取伺服器端返回的流 ResponseStream responseStream = http.sendSync(HttpMethod.POST, url, params); s = responseStream.readString(); } catch (Exception e) { e.printStackTrace(); } return s;
ResponseStream responseStream = http.sendSync(method, url, params);
下面附上發送POST請求的完整代碼:
/** * 發送POST請求,攜帶json和多個檔案參數得到伺服器返回的結果(json格式) * * @param url 請求地址 * @param json 請求體中封裝的json字串 * @param List<File> 上傳多個檔案 * @return String 伺服器返回的結果 */ public static String sendPost(String url, String json, List<File> files) { HttpUtils http = new HttpUtils(); RequestParams params = new RequestParams(); params.addBodyParameter("json", json); if (files.size() == 1) { try { params.addBodyParameter("file", new FileInputStream(files.get(0)), files.get(0) .length(), files.get(0).getName(), "application/octet-stream"); } catch (FileNotFoundException e) { e.printStackTrace(); } } else { for (int i = 0; i < files.size(); i++) { if (files.get(i) != null) { try { params.addBodyParameter("file" + i, new FileInputStream(files.get(i)), files.get(i) .length(), files.get(i).getName(), "application/octet-stream"); } catch (FileNotFoundException e) { e.printStackTrace(); } } } } String s = null; try { // 同步方法,擷取伺服器端返回的流 ResponseStream responseStream = http.sendSync(HttpMethod.POST, url, params); s = responseStream.readString(); } catch (Exception e) { e.printStackTrace(); } return s; }
使用xutils發送POST請求,攜帶json和圖片二進位檔案資料擷取伺服器端返回json資料