Android HttpsURLConnection get、post 访问网络
2016-01-15 15:24
393 查看
证书验证类,此处默认通过所有证书HttpUtils 类public class HttpUtils {
public static void trustAllHosts() {
final String TAG = "trustAllHosts";
// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[] {};
}
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
LogF.i(TAG, "checkClientTrusted");
}
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
LogF.i(TAG, "checkServerTrusted");
}
} };
// Install the all-trusting trust manager
try {
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (Exception e) {
e.printStackTrace();
}
}}
final static HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
1、get 请求
/**
* get方式请求服务器
*
* @param param 请求时包含的参数
* @return
*/
public static String get(RequestParam param) throws IOException, ServerException {
String urlString = param.getUrl();
if (TextUtils.isEmpty(urlString))
return null; HttpURLConnection httpURLConnection = null; HttpsURLConnection https = null;
BufferedReader bufferedReader = null;
try { URL url = new URL(urlString); HttpUtils.trustAllHosts(); // 打开连接 if (url.getProtocol().toLowerCase().equals("https")) { https = (HttpsURLConnection) url.openConnection(); https.setHostnameVerifier(DO_NOT_VERIFY); httpURLConnection = https; } else { httpURLConnection = (HttpURLConnection) url.openConnection(); } //设置读取超时 //设置连接超时
httpURLConnection.setReadTimeout(10 * 1000);
httpURLConnection.setConnectTimeout(5 * 1000);
// Set the post method. Default is GET
httpURLConnection.setRequestMethod("GET");
httpURLConnection.connect();
if (httpURLConnection.getResponseCode() == 200) {
bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream(), "UTF-8"));
StringBuffer stringBuffer = new StringBuffer();
String lineStr = "";
while ((lineStr = bufferedReader.readLine()) != null) {
stringBuffer.append(lineStr + "\n");
}
return stringBuffer.toString();
} else {
Log.w("HTTP", "请求服务器异常 " + httpURLConnection.getResponseCode());
throw new ServerException("服务器异常:" + httpURLConnection.getResponseCode());
}
} finally {
if(bufferedReader != null)
bufferedReader.close();
if(httpURLConnection != null) httpURLConnection.disconnect(); if(https != null) https.disconnect(); } }
2、post 请求
/**
* post 方式请求服务器
*
* @param param 请求参数
* @return 响应 json 串
* @throws IOException 文本异常,超时等
*/
public static String post(RequestParam param) throws IOException, ServerException {
String urlString = param.getUrl();
if (TextUtils.isEmpty(urlString))
return null; HttpURLConnection httpURLConnection = null; HttpsURLConnection https = null;
OutputStreamWriter outputStreamWriter = null;
BufferedReader bufferedReader = null;
try {
//url
URL url = new URL(urlString); HttpUtils.trustAllHosts(); // 打开连接 if (url.getProtocol().toLowerCase().equals("https")) { https = (HttpsURLConnection) url.openConnection(); https.setHostnameVerifier(DO_NOT_VERIFY); httpURLConnection = https; } else { httpURLConnection = (HttpURLConnection) url.openConnection(); } //设置读取超时
//设置连接超时
httpURLConnection.setReadTimeout(10 * 1000);
httpURLConnection.setConnectTimeout(5 * 1000);
// Read from the connection. Default is true.
httpURLConnection.setDoInput(true);
// Output to the connection. Default is
// false, set to true because post
// method must write something to the
// connection
// 设置是否向connection输出,因为这个是post请求,参数要放在http正文内,因此需要设为true
httpURLConnection.setDoOutput(true);
// Post cannot use caches
// Post 请求不能使用缓存
httpURLConnection.setUseCaches(false);
// Set the post method. Default is GET
httpURLConnection.setRequestMethod("POST");
// This method takes effects to
// every instances of this class.
// URLConnection.setFollowRedirects是static函数,作用于所有的URLConnection对象。
// connection.setFollowRedirects(true);
// This methods only
// takes effacts to this
// instance.
// URLConnection.setInstanceFollowRedirects是成员函数,仅作用于当前函数
httpURLConnection.setInstanceFollowRedirects(true);
// Set the content type to urlencoded,
// because we will write
// some URL-encoded content to the
// connection. Settings above must be set before connect!
// 配置本次连接的Content-type,配置为application/x-www-form-urlencoded的
// 意思是正文是urlencoded编码过的form参数,下面我们可以看到我们对正文内容使用URLEncoder.encode
// 进行编码
httpURLConnection.setRequestProperty("Accept-Charset", "UTF-8");
httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// 连接,从postUrl.openConnection()至此的配置必须要在connect之前完成,
// 要注意的是connection.getOutputStream会隐含的进行connect。
httpURLConnection.connect();
// DataOutputStream dataOutputStream = new DataOutputStream(httpURLConnection.getOutputStream());
// dataOutputStream.writeBytes(param.getParams());
// dataOutputStream.flush();
// dataOutputStream.close(); // flush and close//
outputStreamWriter = new OutputStreamWriter(httpURLConnection.getOutputStream(), "UTF-8");
outputStreamWriter.write(param.getParams());
outputStreamWriter.flush();
if (httpURLConnection.getResponseCode() == 200) {
bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream(), "UTF-8"));
StringBuffer stringBuffer = new StringBuffer();
String lineStr = "";
while ((lineStr = bufferedReader.readLine()) != null) {
stringBuffer.append(lineStr + "\n");
}
return stringBuffer.toString();
} else {
Log.w("HTTP", "请求服务器异常 " + httpURLConnection.getResponseCode());
throw new ServerException("服务器异常:" + httpURLConnection.getResponseCode());
}
} finally {
if(bufferedReader != null)
bufferedReader.close();
if(outputStreamWriter != null)
outputStreamWriter.close();
if(httpURLConnection != null) httpURLConnection.disconnect(); if(https != null) https.disconnect(); } }
RequestParam类/*** 描述:网络 请求参数 * @author HJK
*/
public class RequestParam {
private String url;
private Map<String, Object> params;
public void put(String key, String value) {
if (params == null)
params = new HashMap<String, Object>();
params.put(key, value);
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public List<NameValuePair> postParams() {
if (params == null)
return null;
List<NameValuePair> param = new ArrayList<NameValuePair>();
for (String key:params.keySet())
param.add(new BasicNameValuePair(key, params.get(key)+""));
return param;
}
public String getParams() {
if (params == null)
return null;
StringBuffer stringBuffer = new StringBuffer();
for (String key : params.keySet()) {
stringBuffer.append(key).append("=").append(params.get(key)).append("&");
}
if(stringBuffer.length()>0)
stringBuffer.deleteCharAt(stringBuffer.length()-1);
return stringBuffer.toString();
}
public String toString() {
return params == null?null:params.toString();
}
}
ServerException类/**
* 描述:服务器异常
* @author HJK
*/
public class ServerException extends Exception {
public ServerException() {
super();
}
public ServerException(String msg) {
super(msg);
}
public ServerException(String msg, Throwable cause) {
super(msg, cause);
}
public ServerException(Throwable cause) {
super(cause);
}}
public static void trustAllHosts() {
final String TAG = "trustAllHosts";
// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[] {};
}
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
LogF.i(TAG, "checkClientTrusted");
}
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
LogF.i(TAG, "checkServerTrusted");
}
} };
// Install the all-trusting trust manager
try {
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (Exception e) {
e.printStackTrace();
}
}}
final static HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
1、get 请求
/**
* get方式请求服务器
*
* @param param 请求时包含的参数
* @return
*/
public static String get(RequestParam param) throws IOException, ServerException {
String urlString = param.getUrl();
if (TextUtils.isEmpty(urlString))
return null; HttpURLConnection httpURLConnection = null; HttpsURLConnection https = null;
BufferedReader bufferedReader = null;
try { URL url = new URL(urlString); HttpUtils.trustAllHosts(); // 打开连接 if (url.getProtocol().toLowerCase().equals("https")) { https = (HttpsURLConnection) url.openConnection(); https.setHostnameVerifier(DO_NOT_VERIFY); httpURLConnection = https; } else { httpURLConnection = (HttpURLConnection) url.openConnection(); } //设置读取超时 //设置连接超时
httpURLConnection.setReadTimeout(10 * 1000);
httpURLConnection.setConnectTimeout(5 * 1000);
// Set the post method. Default is GET
httpURLConnection.setRequestMethod("GET");
httpURLConnection.connect();
if (httpURLConnection.getResponseCode() == 200) {
bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream(), "UTF-8"));
StringBuffer stringBuffer = new StringBuffer();
String lineStr = "";
while ((lineStr = bufferedReader.readLine()) != null) {
stringBuffer.append(lineStr + "\n");
}
return stringBuffer.toString();
} else {
Log.w("HTTP", "请求服务器异常 " + httpURLConnection.getResponseCode());
throw new ServerException("服务器异常:" + httpURLConnection.getResponseCode());
}
} finally {
if(bufferedReader != null)
bufferedReader.close();
if(httpURLConnection != null) httpURLConnection.disconnect(); if(https != null) https.disconnect(); } }
2、post 请求
/**
* post 方式请求服务器
*
* @param param 请求参数
* @return 响应 json 串
* @throws IOException 文本异常,超时等
*/
public static String post(RequestParam param) throws IOException, ServerException {
String urlString = param.getUrl();
if (TextUtils.isEmpty(urlString))
return null; HttpURLConnection httpURLConnection = null; HttpsURLConnection https = null;
OutputStreamWriter outputStreamWriter = null;
BufferedReader bufferedReader = null;
try {
//url
URL url = new URL(urlString); HttpUtils.trustAllHosts(); // 打开连接 if (url.getProtocol().toLowerCase().equals("https")) { https = (HttpsURLConnection) url.openConnection(); https.setHostnameVerifier(DO_NOT_VERIFY); httpURLConnection = https; } else { httpURLConnection = (HttpURLConnection) url.openConnection(); } //设置读取超时
//设置连接超时
httpURLConnection.setReadTimeout(10 * 1000);
httpURLConnection.setConnectTimeout(5 * 1000);
// Read from the connection. Default is true.
httpURLConnection.setDoInput(true);
// Output to the connection. Default is
// false, set to true because post
// method must write something to the
// connection
// 设置是否向connection输出,因为这个是post请求,参数要放在http正文内,因此需要设为true
httpURLConnection.setDoOutput(true);
// Post cannot use caches
// Post 请求不能使用缓存
httpURLConnection.setUseCaches(false);
// Set the post method. Default is GET
httpURLConnection.setRequestMethod("POST");
// This method takes effects to
// every instances of this class.
// URLConnection.setFollowRedirects是static函数,作用于所有的URLConnection对象。
// connection.setFollowRedirects(true);
// This methods only
// takes effacts to this
// instance.
// URLConnection.setInstanceFollowRedirects是成员函数,仅作用于当前函数
httpURLConnection.setInstanceFollowRedirects(true);
// Set the content type to urlencoded,
// because we will write
// some URL-encoded content to the
// connection. Settings above must be set before connect!
// 配置本次连接的Content-type,配置为application/x-www-form-urlencoded的
// 意思是正文是urlencoded编码过的form参数,下面我们可以看到我们对正文内容使用URLEncoder.encode
// 进行编码
httpURLConnection.setRequestProperty("Accept-Charset", "UTF-8");
httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// 连接,从postUrl.openConnection()至此的配置必须要在connect之前完成,
// 要注意的是connection.getOutputStream会隐含的进行connect。
httpURLConnection.connect();
// DataOutputStream dataOutputStream = new DataOutputStream(httpURLConnection.getOutputStream());
// dataOutputStream.writeBytes(param.getParams());
// dataOutputStream.flush();
// dataOutputStream.close(); // flush and close//
outputStreamWriter = new OutputStreamWriter(httpURLConnection.getOutputStream(), "UTF-8");
outputStreamWriter.write(param.getParams());
outputStreamWriter.flush();
if (httpURLConnection.getResponseCode() == 200) {
bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream(), "UTF-8"));
StringBuffer stringBuffer = new StringBuffer();
String lineStr = "";
while ((lineStr = bufferedReader.readLine()) != null) {
stringBuffer.append(lineStr + "\n");
}
return stringBuffer.toString();
} else {
Log.w("HTTP", "请求服务器异常 " + httpURLConnection.getResponseCode());
throw new ServerException("服务器异常:" + httpURLConnection.getResponseCode());
}
} finally {
if(bufferedReader != null)
bufferedReader.close();
if(outputStreamWriter != null)
outputStreamWriter.close();
if(httpURLConnection != null) httpURLConnection.disconnect(); if(https != null) https.disconnect(); } }
RequestParam类/*** 描述:网络 请求参数 * @author HJK
*/
public class RequestParam {
private String url;
private Map<String, Object> params;
public void put(String key, String value) {
if (params == null)
params = new HashMap<String, Object>();
params.put(key, value);
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public List<NameValuePair> postParams() {
if (params == null)
return null;
List<NameValuePair> param = new ArrayList<NameValuePair>();
for (String key:params.keySet())
param.add(new BasicNameValuePair(key, params.get(key)+""));
return param;
}
public String getParams() {
if (params == null)
return null;
StringBuffer stringBuffer = new StringBuffer();
for (String key : params.keySet()) {
stringBuffer.append(key).append("=").append(params.get(key)).append("&");
}
if(stringBuffer.length()>0)
stringBuffer.deleteCharAt(stringBuffer.length()-1);
return stringBuffer.toString();
}
public String toString() {
return params == null?null:params.toString();
}
}
ServerException类/**
* 描述:服务器异常
* @author HJK
*/
public class ServerException extends Exception {
public ServerException() {
super();
}
public ServerException(String msg) {
super(msg);
}
public ServerException(String msg, Throwable cause) {
super(msg, cause);
}
public ServerException(Throwable cause) {
super(cause);
}}
相关文章推荐
- 证券数据爬取
- HttpClient使用详解
- 关于Linux内核网络架构书籍收集
- Android 使用Xutils报的一个Http类API过时问题
- linux 网络编程(加部分原创)
- 160115http通迅失败 报 Application Transport Security has blocked a cleartext HTTP (http://)
- java基础教程-网络编程(七)
- Android平台下轻量级http网络传输库
- utilize HttpClient to generate a SSL access and generate REST access to fetch data, async programming? cool and brief
- 【Android】TCP轮询扫描局域网设备
- HttpStatusCode 枚举
- MHA的在线切换后的一些总结(mha方案来自网络)
- java通过HTTP访问:POST+GET
- P2P技术基础: 关于TCP打洞技术
- php socket通信(tcp/udp)
- 【bcb 6.0】http相关的控件
- AFNetWorking 检测网络状态
- http://www.tuicool.com/articles/F3Ufyaq
- mrtg监控网络流量简单配置
- 关于mha手动切换的一些记录(mha方案来自网络)