Android HttpURLConnection Post 参数 (https)
声明utf-8:
public static String CHARSET_UTF8 = HTTP.UTF_8;
eg:登陆请求方法,通过接口返回结果:
public static void login(String username, String password, ResponseCallbackHandler responseCallbackHandler) {
Map<String, String> params = new HashMap<>();
params.put("username", username);
params.put("password", password);
post("https:/..../login", params, responseCallbackHandler);
}
post请求执行前,网络判断,以及url参数转换:
private static void post(final String url, Map<String, String> _params, final ResponseCallbackHandler responseCallbackHandler) {
if (!NetworkUtils.isNetworkConnected(RunnerApp.getContext())) {
if (responseCallbackHandler != null) {
responseCallbackHandler.onNetworkError();
responseCallbackHandler.onFinish();
}
return;
}
final String params = map2Url(_params);
new Thread(new Runnable() {
@Override
public void run() {
post(url, params, responseCallbackHandler);
}
}).start();
}
map转换成string类型的url参数:
/**
* map转url参数
*/
public static String map2Url(Map<String, String> paramToMap) {
if (null == paramToMap || paramToMap.isEmpty()) {
return null;
}
StringBuffer url = new StringBuffer();
boolean isfist = true;
for (Map.Entry<String, String> entry : paramToMap.entrySet()) {
if (isfist) {
isfist = false;
} else {
url.append("&");
}
url.append(entry.getKey()).append("=");
String value = entry.getValue();
if (!TextUtils.isEmpty(value)) {
try {
url.append(URLEncoder.encode(value, CHARSET_UTF8));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
return url.toString();
}
post执行:(注:这里简单的描述了下接口返回参数而已)。
/**
* post请求
*/
public static void post(String url, String params, ResponseCallbackHandler responseCallbackHandler) {
StringBuffer bufferRes = null;
try {
HttpURLConnection http = initHttps(url, "POST", null);
OutputStream out = http.getOutputStream();
out.write(params.getBytes(CHARSET_UTF8));
out.flush();
out.close(); InputStream in = http.getInputStream();
BufferedReader read = new BufferedReader(new InputStreamReader(in, CHARSET_UTF8));
String valueString = null;
bufferRes = new StringBuffer();
while ((valueString = read.readLine()) != null) {
bufferRes.append(valueString);
}
in.close();
if (http != null) {
http.disconnect();// 关闭连接
}
if(responseCallbackHandler != null) {
responseCallbackHandler.onSuccess(bufferRes.toString());
LogUtils.d(tag, "onSuccess");
LogUtils.d(tag, "onSuccess:" + bufferRes.toString());
}
} catch (Exception e) {
e.printStackTrace();
if (responseCallbackHandler != null) {
responseCallbackHandler.onNetworkError();
}
}
if (responseCallbackHandler != null) {
responseCallbackHandler.onFinish();
}
}
实例化HttpURLConnection post请求时,ssl添加权限:
/**
* 初始化http请求参数
*/
private static HttpsURLConnection initHttps(String url, String method, Map<String, String> headers)
throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {
TrustManager[] tm = {new CustomX509TrustManager()};
SSLContext sslContext = SSLContext.getInstance("TLSv1");
sslContext.init(null, tm, new java.security.SecureRandom());
// 从上述SSLContext对象中得到SSLSocketFactory对象
SSLSocketFactory ssf = sslContext.getSocketFactory();
URL _url = new URL(url);
HttpsURLConnection http = (HttpsURLConnection) _url.openConnection();
// 连接超时
http.setConnectTimeout(25000);
// 读取超时 --服务器响应比较慢,增大时间
http.setReadTimeout(25000);
http.setRequestMethod(method);
http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
http.setRequestProperty("User-Agent",
"Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36");
if (null != headers && !headers.isEmpty()) {
for (Map.Entry<String, String> entry : headers.entrySet()) {
http.setRequestProperty(entry.getKey(), entry.getValue());
}
}
http.setSSLSocketFactory(ssf);
http.setDoOutput(true);
http.setDoInput(true);
http.connect();
return http;
}
添加证书管理:
// 证书管理
class CustomX509TrustManager implements X509TrustManager { public X509Certificate[] getAcceptedIssuers() {
return null;
} @Override
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
} @Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
}
参考:
Android SSL - No Peer Certificate
http请求No peer certificate的解决方法(使用的是HTTPClient)
https 用 HttpsURLConnectio如何登陆 post方式
Android HttpURLConnection Post 参数 (https)的更多相关文章
- [Android] HttpURLConnection & HttpClient & Socket
Android的三种网络联接方式 1.标准Java接口:java.net.*提供相关的类//定义地址URL url = new URL("http://www.google.com" ...
- Android Stuido 方法参数 p0,p1
Android Stuido 方法参数 p0,p1 参考文献 https://stackoverflow.com/questions/49219439/incorrect-variable-names ...
- Android HttpURLConnection源代码分析
Android HttpURLConnection源代码分析 之前写过HttpURLConnection与HttpClient的差别及选择.后来又分析了Volley的源代码. 近期又遇到了问题,想在V ...
- android fragment传递参数_fragment之间传值的两种方法
在Activity中加载Fragment的时候.有时候要使用多个Fragment切换.并传值到另外一个Fragment.也就是说两个Fragment之间进行参数的传递.查了很多资料.找到两种方法.一种 ...
- Charles在Mac、iPhone、Android上抓http/https协议的包
1.我使用的版本是4.0.2,下载和破解网上方法很多,不做说明 2.Charles在Mac上抓http/https协议的包 2.1先把这三个都给装上,装完后会自动跳转到钥匙串中 2.2如果装完后提示证 ...
- Android App 安全的HTTPS 通信
漏洞描述 对于数字证书相关概念.Android 里 https 通信代码就不再复述了,直接讲问题.缺少相应的安全校验很容易导致中间人攻击,而漏洞的形式主要有以下3种: 自定义X509TrustMana ...
- Android HttpURLConnection.connect找不到源 HttpURLConnection连接失败 HttpURLConnection.connect IO异常 解决办法
Android HttpURLConnection.connect找不到源 HttpURLConnection连接失败 HttpURLConnection.connect IO异常 解决办法 以下代 ...
- Android HttpURLConnection And HttpClient
Google的工程师的一个博客写到: HttpURLConnection和HttpClient Volley HTTP请求时:在Android 2.3及以上版本,使用的是HttpURLConnecti ...
- [转]Fiddler抓取Android真机上的HTTPS包
此篇文章转载自:http://blog.csdn.net/roland_sun/article/details/30078353 工作中经常会需要对一些app进行抓包, 但是每次默认都是只抓http请 ...
随机推荐
- Android Tab -- 使用ViewPager、PagerAdapter来实现
原文地址:http://blog.csdn.net/crazy1235/article/details/42678877 效果:滑动切换,自动切换. 代码:https://github.com/ldb ...
- JDBC 精度
http://www.cnblogs.com/tobecrazy/p/3390021.html http://www.cnblogs.com/kerrycode/p/4034231.html http ...
- Linux(CentOS)常用操作指令(二)
1.安装wget指令: yum -y install wget 2.安装ifconfig指令: yum install net-tools 3.tar解压文件的使用: tar -zxvf aaa. ...
- Vmware 中安装Unix
准备 1. ubuntu 14.10 下载地址: 官网下载链接 http://www.ubuntu.com/download/desktop 官方版本库 http://releases.ubuntu. ...
- SQL常用方言列表
DB2 org.hibernate.dialect.DB2Dialect DB2 AS/400 org.hibernate.dialect.DB2400Dialect DB2 OS390 org.hi ...
- Oralce sysaux WRH$_ACTIVE_SESSION_HISTORY清理
In this Document Symptoms Cause Solution References Symptoms sysaux表空間的WRH$_ACTIVE_SESSION_HISTORY表變 ...
- SimpleHashTable
简单的Hash Table 实现,下次被问到,至少不是从0开始.不过笔试问这个毕竟不多. public struct Item<K, V> { public K Key { get; se ...
- wp8 入门到精通 MultiMsgPrompt
List<NotifyMsg> arraymsg = new List<NotifyMsg>(); List<NotifyInfo> ArrayNotifyInfo ...
- php开启mysqli扩展之后如何连接数据库
Mysqli是php5之后才有的功能,没有开启扩展的朋友可以打开您的php.ini的配置文件;相对于mysql有很多新的特性和优势,需要了解的朋友可以参考下 Mysqli是php5之后才有的功能,没有 ...
- WPF PRISM开发入门一( 初始化PRISM WPF程序)
这篇博客将介绍在WPF项目中引入PRISM框架进行开发的一些基础知识.目前最新的PRISM的版本是Prism 6.1.0,可以在Github上获取PRISM的源码.这个系列的博客将选择PRISM 4. ...