博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Android HttpURLConnection Post 参数 (https)
阅读量:5068 次
发布时间:2019-06-12

本文共 5735 字,大约阅读时间需要 19 分钟。

声明utf-8:

1 public static String CHARSET_UTF8 = HTTP.UTF_8;

eg:登陆请求方法,通过接口返回结果:

1 public static void login(String username, String password, ResponseCallbackHandler responseCallbackHandler) {2         Map
params = 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(Map
paramToMap) { 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, Map
headers) 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)

转载于:https://www.cnblogs.com/CharlesGrant/p/5088967.html

你可能感兴趣的文章
【AS3代码】播放FLV视频流的三步骤!
查看>>
枚举的使用
查看>>
luogu4849 寻找宝藏 (cdq分治+dp)
查看>>
日志框架--(一)基础篇
查看>>
关于源程序到可运行程序的过程
查看>>
转载:mysql数据库密码忘记找回方法
查看>>
scratch少儿编程第一季——06、人在江湖混,没有背景怎么行。
查看>>
【贪心+DFS】D. Field expansion
查看>>
C# Async与Await的使用
查看>>
Mysql性能调优
查看>>
iOS基础-UIKit框架-多控制器管理-实例:qq界面框架
查看>>
自定义tabbar(纯代码)
查看>>
小程序底部导航栏
查看>>
poj1611 简单并查集
查看>>
Ubuntu 14.04下安装CUDA8.0
查看>>
跨平台开发 -- C# 使用 C/C++ 生成的动态链接库
查看>>
C# BS消息推送 SignalR介绍(一)
查看>>
WPF星空效果
查看>>
WPF Layout 系统概述——Arrange
查看>>
PIGOSS
查看>>