httpclient使用post方式傳送json資料,以及服務端的接收
阿新 • • 發佈:2019-01-08
步驟大致如下:
1、客戶端使用StringEntity封裝資料
2、服務端先從request.getInputStream();中獲取資料,再把位元組流轉為字元流
3、最後用response.getWriter().write(param);返回資料給客戶端
4、客戶端使用httpResponse.getEntity()..getContent()獲得InputStream
//下面是客戶端的程式碼,使用了StringEntity
//requestContent為請求的JSON資料 public static InputStream postRequestStreamNew(String destUrl, String requestContent,String amothed,BasicHeader[] aheader) throws ClientProtocolException, IOException { BasicHttpParams params = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(params, 30 * 1000); HttpProtocolParams.setUserAgent(params, "MOBILE"); HttpPost request = null; HttpRequestBase httpPost = null; if (amothed.equals(POST)) { //防止中文亂碼 StringEntity requestEntity = new StringEntity(URLEncoder.encode(requestContent, "UTF-8")); httpPost = new HttpPost(destUrl); ((HttpPost) httpPost).setEntity(requestEntity); } else { String temp = URLEncoder.encode(requestContent); httpPost = new HttpGet(destUrl + "?param=" + temp); } if (aheader != null) { for (BasicHeader ah : aheader) { httpPost.addHeader(ah); } } //HttpClient httpClient = getNewHttpClientByHttps(); HttpClient httpClient = getNewHttpClientByHttp(); if (getNetType() != WIFI_INT) { InetSocketAddress pxy = getProxy(); if (pxy != null) { HttpHost proxy = new HttpHost(pxy.getHostName(), pxy.getPort()); httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); } } HttpResponse httpResponse; InputStream responseContent = null; try { if (GlobalVariable.IS_FUSION) { httpResponse = httpClient.execute(request); } else { httpResponse = httpClient.execute(httpPost); } int rescode = httpResponse.getStatusLine().getStatusCode(); HttpEntity responseEntity = httpResponse.getEntity(); responseContent = responseEntity.getContent(); } catch (Exception e) { Log.e(TAG, "postRequestStream", e); } return responseContent; } public static HttpClient getNewHttpClientByHttps() { HttpClient ht = null; try { KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(null, null); SSLSocketFactory sf = new SSLSocketFactoryEx(trustStore); sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); registry.register(new Scheme("https", sf, 443)); ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry); ht = new DefaultHttpClient(ccm, params); } catch (Exception e) { Log.e(TAG, "getNewHttpClient", e); // return new DefaultHttpClient(); } if (ht == null) { ht = new DefaultHttpClient(); } // 請求超時,10s建立連線應該夠了 ht.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10 * 1000); // 讀取超時, 設定成120s這個比較大的時間是因為資料量大的時候傳輸時間會比較久 ht.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 120 * 1000); return ht; } public static HttpClient getNewHttpClientByHttp() { HttpClient ht = new DefaultHttpClient(); // 請求超時,10s建立連線應該夠了 ht.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10 * 1000); // 讀取超時, 設定成120s這個比較大的時間是因為資料量大的時候傳輸時間會比較久 ht.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 120 * 1000); return ht; } //處理服務端返回的資料 private static String convertStreamToString(InputStream is) throws UnsupportedEncodingException { if (is == null) { return "{\"code\":\"123\"}"; } BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8")); StringBuilder sb = new StringBuilder(); String line = null; try { while ((line = reader.readLine()) != null) { sb.append(line); } } catch (IOException e) { Log.e(TAG, "convertStreamToString", e); } finally { try { is.close(); } catch (IOException e) { Log.e(TAG, "convertStreamToString", e); } } return sb.toString(); } //下面是服務端的程式碼: //解析手機傳遞過來的資料的Servlet public class HcServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //解析返回的資料 String requestData = getParamByStream(request); //業務處理的程式碼... //返回資料 JSONObject data = new JSONObject(); data.put("returnCode", "0"); sendParam(response,requestData ); } /** * 從客戶端傳來的請求流中獲得請求引數 * @param request * @return String */ public static String getParamByStream(HttpServletRequest request){ String param = ""; InputStream is = null; InputStreamReader isr = null; BufferedReader br = null; try { StringBuffer sb = new StringBuffer(); is = request.getInputStream(); isr = new InputStreamReader(is, "UTF-8"); br = new BufferedReader(isr); String s = ""; while ((s = br.readLine()) != null) { sb.append(s); } param = sb.toString(); param = URLDecoder.decode(param, "UTF-8"); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } finally { try { if (br != null) { br.close(); } if (isr != null) { isr.close(); } if (is != null) { is.close(); } } catch (IOException e) { e.printStackTrace(); } } return param; } /** * 向手機客戶端傳送引數 */ public static void sendParam(HttpServletResponse response, String param){ try { response.setCharacterEncoding("utf-8"); response.getWriter().write(param); } catch (IOException e) { e.printStackTrace(); } } }