声明utf-8:
1 public static String CHARSET_UTF8 = HTTP.UTF_8;
eg:登陆请求方法,通过接口返回结果:
1 public static void login(String username, String password, ResponseCallbackHandler responseCallbackHandler) {2 Mapparams = new HashMap<>();3 params.put("username", username);4 params.put("password", password);5 post("https:/..../login", params, responseCallbackHandler);6 }
post请求执行前,网络判断,以及url参数转换:
1 private static void post(final String url, Map_params, final ResponseCallbackHandler responseCallbackHandler) { 2 3 if (!NetworkUtils.isNetworkConnected(RunnerApp.getContext())) { 4 if (responseCallbackHandler != null) { 5 responseCallbackHandler.onNetworkError(); 6 responseCallbackHandler.onFinish(); 7 } 8 return; 9 }10 final String params = map2Url(_params);11 new Thread(new Runnable() {12 @Override13 public void run() {14 post(url, params, responseCallbackHandler);15 }16 }).start();17 }
map转换成string类型的url参数:
1 /** 2 * map转url参数 3 */ 4 public static String map2Url(MapparamToMap) { 5 if (null == paramToMap || paramToMap.isEmpty()) { 6 return null; 7 } 8 StringBuffer url = new StringBuffer(); 9 boolean isfist = true;10 for (Map.Entry entry : paramToMap.entrySet()) {11 if (isfist) {12 isfist = false;13 } else {14 url.append("&");15 }16 url.append(entry.getKey()).append("=");17 String value = entry.getValue();18 if (!TextUtils.isEmpty(value)) {19 try {20 url.append(URLEncoder.encode(value, CHARSET_UTF8));21 } catch (UnsupportedEncodingException e) {22 e.printStackTrace();23 }24 }25 }26 return url.toString();27 }
post执行:(注:这里简单的描述了下接口返回参数而已)。
1 /** 2 * post请求 3 */ 4 public static void post(String url, String params, ResponseCallbackHandler responseCallbackHandler) { 5 StringBuffer bufferRes = null; 6 try { 7 HttpURLConnection http = initHttps(url, "POST", null); 8 OutputStream out = http.getOutputStream(); 9 out.write(params.getBytes(CHARSET_UTF8));10 out.flush();11 out.close();12 13 InputStream in = http.getInputStream();14 BufferedReader read = new BufferedReader(new InputStreamReader(in, CHARSET_UTF8));15 String valueString = null;16 bufferRes = new StringBuffer();17 while ((valueString = read.readLine()) != null) {18 bufferRes.append(valueString);19 }20 in.close();21 if (http != null) {22 http.disconnect();// 关闭连接23 }24 if(responseCallbackHandler != null) {25 responseCallbackHandler.onSuccess(bufferRes.toString());26 LogUtils.d(tag, "onSuccess");27 LogUtils.d(tag, "onSuccess:" + bufferRes.toString());28 }29 } catch (Exception e) {30 e.printStackTrace();31 if (responseCallbackHandler != null) {32 responseCallbackHandler.onNetworkError();33 }34 }35 if (responseCallbackHandler != null) {36 responseCallbackHandler.onFinish();37 }38 }
实例化HttpURLConnection post请求时,ssl添加权限:
1 /** 2 * 初始化http请求参数 3 */ 4 private static HttpsURLConnection initHttps(String url, String method, Mapheaders) 5 throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException { 6 TrustManager[] tm = { new CustomX509TrustManager()}; 7 SSLContext sslContext = SSLContext.getInstance("TLSv1"); 8 sslContext.init(null, tm, new java.security.SecureRandom()); 9 // 从上述SSLContext对象中得到SSLSocketFactory对象10 SSLSocketFactory ssf = sslContext.getSocketFactory();11 URL _url = new URL(url);12 HttpsURLConnection http = (HttpsURLConnection) _url.openConnection();13 // 连接超时14 http.setConnectTimeout(25000);15 // 读取超时 --服务器响应比较慢,增大时间16 http.setReadTimeout(25000);17 http.setRequestMethod(method);18 http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");19 http.setRequestProperty("User-Agent",20 "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36");21 if (null != headers && !headers.isEmpty()) {22 for (Map.Entry entry : headers.entrySet()) {23 http.setRequestProperty(entry.getKey(), entry.getValue());24 }25 }26 http.setSSLSocketFactory(ssf);27 http.setDoOutput(true);28 http.setDoInput(true);29 http.connect();30 return http;31 }
添加证书管理:
1 // 证书管理 2 class CustomX509TrustManager implements X509TrustManager { 3 4 public X509Certificate[] getAcceptedIssuers() { 5 return null; 6 } 7 8 @Override 9 public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {10 }11 12 @Override13 public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {14 }15 }
参考:
(使用的是HTTPClient)