Android Http请求
Android HTTP请求封装代码
/**
* This class is the Utils of other classes.
*/
public class HttpUtil {
/** 变量/常量说明 */
private static final String TAG = "HttpUtils";
/** 超时时间 */
private static int mTimeOut = 20000;
/** 私钥密码 */
/** 使用协议 */
private static final String CLIENT_AGREEMENT = "TLS";
/** 密钥管理器 */
/** 变量/常量说明 */
private static HttpUtil mHttpUtils = null; /**
* 获取HPPS对象实例
*
* @param application
* @return
* @since V1.0
*/
public static HttpUtil getInstace(Context context) {
if (mHttpUtils == null) {
mHttpUtils = new HttpUtil(context);
}
return mHttpUtils;
} /**
* @param application
*/
private HttpUtil(Context context) {
} /**
* 这里对方法做描述
*
* @param servAddr
* @param xmlBody
* @return
* @throws HttpException
* @since V1.0
*/
public String httpGetRequest(String servAddr) throws HttpException {
// create connection
String response = null;
HttpURLConnection conn = null;
boolean ret = false;
InputStream in = null; try {
URL url = new URL(servAddr);
conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(mTimeOut);
conn.setReadTimeout(mTimeOut);
conn.setDoInput(true);
conn.setRequestMethod("GET");
conn.setRequestProperty("Content-type", "text/xml; charset=utf-8"); if (conn.getResponseCode() == 200) {
// getCookie(conn);
in = new BufferedInputStream(conn.getInputStream());
} else {
in = new BufferedInputStream(conn.getErrorStream());
} response = inputStream2String(in); in.close();
in = null;
ret = true;
} catch (MalformedURLException e) {
ret = false;
e.printStackTrace();
} catch (ProtocolException e) {
ret = false;
e.printStackTrace();
} catch (IOException e) {
ret = false;
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
in = null;
}
if (conn != null) {
// 断开连接
conn.disconnect();
conn = null;
}
} // 抛出异常
if (!ret) {
throw new HttpException("network exception", HttpException.HTTP_NETWORD_EXCEPTION);
} return response;
} /**
* 这里对方法做描述
*
* @return
* @throws InvalidFormatException
* @see
* @since V1.0
*/
public static String httpPostRequest(String path) {
// create connection
String response = null;
HttpURLConnection conn = null;
try {
URL url = new URL(path);
conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(mTimeOut);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-type", "text/xml; charset=utf-8"); InputStream in = new BufferedInputStream(conn.getInputStream());
response = inputStream2String(in);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (conn != null) {
// 断开连接
conn.disconnect();
conn = null;
}
} return response;
} /**
* httpPost方式
*
* @param servAddr
* @param xmlBody
* @return
* @throws HttpException
* @since V1.0
*/
public String httpPostRequest(String servAddr, String xmlBody) throws HttpException {
// create connection
String response = null;
HttpURLConnection conn = null;
boolean ret = false;
InputStream in = null;
DataOutputStream os = null;
try {
URL url = new URL(servAddr);
conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(mTimeOut);
conn.setReadTimeout(mTimeOut);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-type", "text/xml; charset=utf-8"); // send xml contant to server
os = new DataOutputStream(conn.getOutputStream());
os.write(xmlBody.getBytes(), 0, xmlBody.getBytes().length);
os.flush();
os.close();
os = null;
if (conn.getResponseCode() == 200) {
// getCookie(conn);
in = new BufferedInputStream(conn.getInputStream());
} else {
in = new BufferedInputStream(conn.getErrorStream());
} response = inputStream2String(in); in.close();
in = null;
ret = true;
} catch (MalformedURLException e) {
ret = false;
e.printStackTrace();
} catch (ProtocolException e) {
ret = false;
e.printStackTrace();
} catch (IOException e) {
ret = false;
e.printStackTrace();
} finally { try {
if (in != null) {
in.close();
}
if (os != null) {
os.close();
}
} catch (IOException e) {
e.printStackTrace();
}
in = null; if (conn != null) {
// 断开连接
conn.disconnect();
conn = null;
}
} // 抛出异常
if (!ret) {
throw new HttpException("network exception", HttpException.HTTP_NETWORD_EXCEPTION);
} return response;
} /**
* 这里对方法做描述
*
* @return
* @throws HttpException
* @see
* @since V1.0
*/
public String httpsGetRequest(String servHttpsAddr) {
if (servHttpsAddr == null || servHttpsAddr.equals("")) {
CLog.d(TAG, "sslGetRequest servHttpsAddr == null");
return "";
} boolean bRet = verifyHttpsUrl(servHttpsAddr);
if (!bRet) {
CLog.d(TAG, "sslGetRequest verifyHttpsUrl fail");
return "";
} String response = "";
try {
response = getSslRequest(servHttpsAddr);
} catch (HttpException e) {
e.printStackTrace();
CLog.d(TAG, "sslGetRequest verifyHttpsUrl fail");
return "";
} return response;
} /**
* httpsPost方式发送
*
* @return
* @throws HttpException
* @see
* @since V1.0
*/
public String httpsPostRequest(String servHttpsAddr, String xmlBody) {
if (servHttpsAddr == null || servHttpsAddr.equals("")) {
CLog.d(TAG, "postHttpsRequest servHttpsAddr == null");
return "";
} if (xmlBody == null || xmlBody.equals("")) {
CLog.d(TAG, "postHttpsRequest xmlBody == null");
return "";
} boolean bRet = verifyHttpsUrl(servHttpsAddr);
if (!bRet) {
CLog.d(TAG, "postHttpsRequest verifyHttpsUrl fail");
return "";
} String response = "";
try {
response = postSslRequest(servHttpsAddr, xmlBody);
} catch (HttpException e) {
e.printStackTrace();
CLog.d(TAG, "postHttpsRequest postSslRequest fail");
return "";
} return response;
} /**
* 把输入流转化成string
*
* @param is
* @return
* @see
* @since V1.0
*/
private static String inputStream2String(InputStream is) {
InputStreamReader inputStreamReader = new InputStreamReader(is);
BufferedReader in = new BufferedReader(inputStreamReader);
StringBuffer buffer = new StringBuffer();
String line = "";
try {
while ((line = in.readLine()) != null) {
buffer.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally { try {
if (inputStreamReader != null) {
inputStreamReader.close();
}
inputStreamReader = null;
if (in != null) {
in.close();
}
in = null;
} catch (IOException e) {
e.printStackTrace();
} }
return buffer.toString();
} /**
* 这里对方法做描述
*
* @param servHttpsAddr
* @param xmlBody
* @return
* @throws HttpException
* @since V1.0
*/
private String getSslRequest(String servHttpsAddr) throws HttpException {
// create connection
String response = null;
HttpURLConnection conn = null;
boolean ret = false;
InputStream in = null;
try {
URL url = new URL(servHttpsAddr);
trustAllHosts();
conn = (HttpsURLConnection) url.openConnection();
((HttpsURLConnection) conn).setHostnameVerifier(DO_NOT_VERIFY);// 不进行主机名确认 // ((HttpsURLConnection)
// conn).setSSLSocketFactory(getPushSSLSocketFactory()); conn.setConnectTimeout(mTimeOut);
conn.setReadTimeout(mTimeOut);
conn.setDoInput(true);
conn.setRequestMethod("GET");
conn.setRequestProperty("Content-type", "text/xml; charset=utf-8"); if (conn.getResponseCode() == 200) {
// getCookie(conn);
in = new BufferedInputStream(conn.getInputStream());
} else {
in = new BufferedInputStream(conn.getErrorStream());
} response = inputStream2String(in); in.close();
in = null;
ret = true;
} catch (MalformedURLException e) {
ret = false;
e.printStackTrace();
} catch (ProtocolException e) {
ret = false;
e.printStackTrace();
} catch (IOException e) {
ret = false;
e.printStackTrace();
}
// catch (NoSuchAlgorithmException e) {
// ret = false;
// e.printStackTrace();
// } catch (KeyManagementException e) {
// ret = false;
// e.printStackTrace();
// } catch (KeyStoreException e) {
// ret = false;
// e.printStackTrace();
// } catch (CertificateException e) {
// ret = false;
// e.printStackTrace();
// } catch (UnrecoverableKeyException e) {
// ret = false;
// e.printStackTrace();
// }
finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
in = null;
}
if (conn != null) {
// 断开连接
conn.disconnect();
conn = null;
}
} // 抛出异常
if (!ret) {
throw new HttpException("network exception", HttpException.HTTP_NETWORD_EXCEPTION);
} return response;
} /**
* 验证https地址
*
* @since V1.0
*/
public boolean verifyHttpsUrl(String httpsAddr) {
// TODO Auto-generated method stub
if (httpsAddr == null || httpsAddr.equals("")) {
CLog.e(TAG, "verifyHttpsUrl httpsAddr == null");
return false;
} URL httpsUurl;
try {
httpsUurl = new URL(httpsAddr);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
CLog.e(TAG, "verifyHttpsUrl httpsAddr not url, error url:" + httpsAddr);
return false;
} if (!httpsUurl.getProtocol().equalsIgnoreCase("https")) {
CLog.e(TAG, "verifyHttpsUrl httpsAddr not https, error url:" + httpsAddr);
return false;
} return true;
} /**
* post ssl请求
*
* @param servHttpsAddr
* @param xmlBody
* @return
* @throws HttpException
* @since V1.0
*/
private String postSslRequest(String servHttpsAddr, String xmlBody) throws HttpException {
// 回复信令
String response = null;
//
boolean ret = false;
// 输入流
InputStream in = null;
DataOutputStream os = null;
HttpsURLConnection httpsConn = null;
InputStream inputStream = null;
try {
URL url = new URL(servHttpsAddr); // solution: javax.net.ssl.SSLException: Not trusted server
// certificate
trustAllHosts(); // 打开连接
httpsConn = (HttpsURLConnection) url.openConnection();
// 不进行主机名确认
httpsConn.setHostnameVerifier(DO_NOT_VERIFY);
httpsConn.setConnectTimeout(mTimeOut);
httpsConn.setReadTimeout(mTimeOut);
httpsConn.setDoInput(true);
httpsConn.setDoOutput(true);
httpsConn.setRequestMethod("POST");
httpsConn.setRequestProperty("Content-type","text/xml; charset=utf-8"); // send xml contant to server
os = new DataOutputStream(httpsConn.getOutputStream());
os.write(xmlBody.getBytes(), 0, xmlBody.getBytes().length);
os.flush();
os.close();
os = null; if (httpsConn.getResponseCode() == 200) {
// getCookie(conn);
inputStream = httpsConn.getInputStream();
in = new BufferedInputStream(inputStream);
} else {
inputStream = httpsConn.getErrorStream();
in = new BufferedInputStream(inputStream);
} response = inputStream2String(in);
if (inputStream != null) {
inputStream.close();
inputStream = null;
} in.close();
in = null;
ret = true;
} catch (MalformedURLException e) {
ret = false;
e.printStackTrace();
} catch (ProtocolException e) {
ret = false;
e.printStackTrace();
} catch (IOException e) {
ret = false;
e.printStackTrace();
} finally { try {
if (inputStream != null) {
inputStream.close();
}
if (in != null) {
in.close();
}
in = null;
if (os != null) {
os.close();
} } catch (IOException e) {
e.printStackTrace();
} if (httpsConn != null) {
// 断开连接
httpsConn.disconnect();
httpsConn = null;
}
} // 抛出异常
if (!ret) {
throw new HttpException("network exception", HttpException.HTTP_NETWORD_EXCEPTION);
} return response;
} /** always verify the host - dont check for certificate */
final static HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
}; /**
* Trust every server - dont check for any certificate
*
* @since V1.0
*/
private static void 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 {
} public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
} }; // Install the all-trusting trust manager
try {
SSLContext sc = SSLContext.getInstance(CLIENT_AGREEMENT);
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (Exception e) {
e.printStackTrace();
}
} /**
* 在此对类做相应的描述 */
public static class _FakeX509TrustManager implements X509TrustManager { /** 变量/常量说明 */
private static TrustManager[] trustManagers;
/** 变量/常量说明 */
private static final X509Certificate[] _AcceptedIssuers = new X509Certificate[] {}; @Override
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
} @Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
} /**
* 这里对方法做描述
*
* @param chain
* @return
* @since V1.0
*/
public boolean isClientTrusted(X509Certificate[] chain) {
return true;
} /**
* 这里对方法做描述
*
* @param chain
* @return
* @since V1.0
*/
public boolean isServerTrusted(X509Certificate[] chain) {
return true;
} /*
* (non-Javadoc)
* @see javax.net.ssl.X509TrustManager#getAcceptedIssuers()
*/
@Override
public X509Certificate[] getAcceptedIssuers() {
return _AcceptedIssuers;
} /**
* 这里对方法做描述
*
* @since V1.0
*/
public static void allowAllSSL() {
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
} }); SSLContext context = null;
if (trustManagers == null) {
trustManagers = new TrustManager[] { new _FakeX509TrustManager() };
} try {
context = SSLContext.getInstance(CLIENT_AGREEMENT);
if (context == null) {
return;
}
context.init(null, trustManagers, new SecureRandom());
SSLSocketFactory defaultSSLSocketFactory = context.getSocketFactory();
if (defaultSSLSocketFactory != null) {
HttpsURLConnection.setDefaultSSLSocketFactory(defaultSSLSocketFactory);
}
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
} }
}
}
Android Http请求的更多相关文章
- 浅论Android网络请求库——android-async-http
在iOS开发中有大名鼎鼎的ASIHttpRequest库,用来处理网络请求操作,今天要介绍的是一个在Android上同样强大的网络请求库android-async-http,目前非常火的应用Insta ...
- Android Http请求框架二:xUtils 框架网络请求
一:对Http不了解的请看 Android Http请求框架一:Get 和 Post 请求 二.正文 1.xUtils 下载地址 github 下载地址 : https://github.com/w ...
- Android Http请求框架一:Get 和 Post 请求
1.HttpUtil package com.app.android01; import java.io.BufferedReader; import java.io.IOException; imp ...
- Android之Http通信——3.Android HTTP请求方式:HttpURLConnection
3.Android HTTP请求方式之HttpURLConnection 引言: 好了,前两节我们已经对HTTP协议进行了学习.相信看完前两节的朋友对HTTP协议相比之前 应该更加熟悉吧.好吧.学了要 ...
- Android网络请求框架AsyncHttpClient实例详解(配合JSON解析调用接口)
最近做项目要求使用到网络,想来想去选择了AsyncHttpClient框架开进行APP开发.在这里把我工作期间遇到的问题以及对AsyncHttpClient的使用经验做出相应总结,希望能对您的学习有所 ...
- xamarin android网络请求总结
xamarin android中网络请求的框架非常多,在项目中使用的是第三方的一个网络请求框架restsharp,应该是github上.net网络请求最多star的框架,没有之一.这里就简单汇总了其他 ...
- Xamarin Android权限请求
Xamarin Android权限请求 Android权限规定了App是否可以访问特定的资源,如网络.电话和短信.在原有API 6.0之前,App在安全的时候,会请求一次权限.一旦安装后,App就 ...
- Android 网络请求框架Retrofit
Retrofit是Square公司开发的一款针对Android网络请求的框架,Retrofit2底层基于OkHttp实现的,OkHttp现在已经得到Google官方认可,大量的app都采用OkHttp ...
- Android 网络请求及数据处理
Android 网络请求: 1.Volley http://blog.csdn.net/t12x3456/article/details/9221611 2.Android-Async-Http ...
随机推荐
- PHP之算法偶遇隨感
php真的很棒,很多函數把我們想要的功能都簡單實現了,是項目快速開發的首選.說實話,在BS程序開發方面我認為最好的兩種語言是PHP和JSP,我之前曾學過一段時間的java,確實很棒完全的OOP,但是它 ...
- SQL Server 2008 Datetime Cast 成 Date 类型可以使用索引(转载)
很久没写blog,不是懒,实在是最近我这的访问速度不好,用firefox经常上传不了图片 ....... 今天无意发现了SQL Server 2008 Datetime Cast 成 Date 类型可 ...
- 了解 JavaScript (4)– 第一个 Web 应用程序
在下面的例子中,我们将要构建一个 Bingo 卡片游戏,每个示例演示 JavaScript 的不同方面,通过每次的改进将会得到最终有效的 Bingo 卡片. Bingo 卡片的内容 美国 Bingo ...
- mysql 日期对比,varchar类型装换为datetime类型
select * from tb_gps WHERE str_to_date(intime,'%Y-%m-%d %H:%i:%s') BETWEEN '2013-9-2 14:40:33' and ' ...
- linux shell脚本备份mysql数据库
#!/bin/sh # 备份数据库 # Mysql 用户名密码 MYSQL_USER=root MYSQL_PASS=root BACKUP_DIR=/data/backup/mysql DATA_D ...
- Django 源码小剖: 更高效的 URL 调度器(URL dispatcher)
效率问题 django 内部的 url 调度机制说白了就是给一张有关匹配信息的表, 这张表中有着 url -> action 的映射, 当请求到来的时候, 一个一个(遍历)去匹配. 中, 则调用 ...
- ECSHOP会员登录后直接进用户中心
ECSHOP系统在会员登录成功后,不是直接进入用户中心,而是跳转回了上一个页面或者是跳转到了首页. 注意:这里说的是,用户没有主动点击前往哪个页面,让系统自动跳转. 那如何让会员登录成功后自动进入“用 ...
- WCF实例上下文模式与并发模式对性能的影响
实例上下文模式 InstanceContextMode 控制在响应客户端调用时,如何分配服务实例.InstanceContextMode 可以设置为以下值: •Single – 为所有客户端调用分配一 ...
- 关于"The dependency was added by the project system and cannot be removed" Error
阅读一个简单地工程代码,其中一个工程BaseCode是 static lib,另一个工程RunBaseCode使用该lib,但在工程设置的“Linker\Input\AdditionalDepende ...
- Android中用layer-list编写阴影效果
要实现这种效果当然有多 种方式,比如背景图片直接加阴影效果,或者用代码画一个(onDraw()).这次我们直接用layer-list来实现.在项目 res->drawable中创建一个xml,如 ...