前言
这个工具包在Android6.0之前很火的,但是在Android6.0之后被删除了,无法直接使用了
添加工具类
前面说过,这个工具库无法直接使用,我们就需要添加它到工程里面
在build.grade中加入
android {
useLibrary 'org.apache.http.legacy'
}
现在,就可以是用HttpClient相关的类了
如何使用
get请求
在get请求中,我们需要分五步走:
1、设置HttpParam基本参数
//Instantiation HttpParams
HttpParams params = new BasicHttpParams();
/**
* Set HttpClientConnection Params
*/
//Set ConnectionTimeOut
HttpConnectionParams.setConnectionTimeout(params,5000);
//Set SoTimeOut
HttpConnectionParams.setSoTimeout(params,5000);
//Set Tcp No Delay
HttpConnectionParams.setTcpNoDelay(params,true);
/**
* Set HttpClientProtocol Params
*/
//Set Http Version
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
//Set Http Charaset
HttpProtocolParams.setContentCharset(params,HTTP.UTF_8);
//Set Http keepAlive
HttpProtocolParams.setUseExpectContinue(params,true);
2、初始化HttpClient
HttpClient client = new DefaultHttpClient(params);
3、初始化HttpGet
HttpGet mget = new HttpGet(url);
4、执行Client得到HttpResponse
HttpResponse httpResponse = client.execute(mget);
5、解析HttpResponse得到其中的数据
int code = httpResponse.getStatusLine().getStatusCode();
HttpEntity entity = httpResponse.getEntity();
InputStream inputStream = entity.getContent();
Post请求
在post请求中,我们需要分七步走:
1、同样去设置请去参数
//Instantiation HttpParams
HttpParams params = new BasicHttpParams();
/**
* Set HttpClientConnection Params
*/
//Set ConnectionTimeOut
HttpConnectionParams.setConnectionTimeout(params,5000);
//Set SoTimeOut
HttpConnectionParams.setSoTimeout(params,5000);
//Set Tcp No Delay
HttpConnectionParams.setTcpNoDelay(params,true);
/**
* Set HttpClientProtocol Params
*/
//Set Http Version
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
//Set Http Charaset
HttpProtocolParams.setContentCharset(params,HTTP.UTF_8);
//Set Http keepAlive
HttpProtocolParams.setUseExpectContinue(params,true);
2、初始化HttpClient
HttpClient client = new DefaultHttpClient(params);
3、初始化HttpGet
HttpPost mpost = new HttpPost(url);
4、添加请求头
mpost.addHeader("Connection", "Keep-Alive");
5、添加请求参数
List<NameValuePair> pairs = new ArrayList<>();
pairs.add(new BasicNameValuePair(name, value));
mpost.setEntity(new UrlEncodedFormEntity(pairs));
6、执行Client得到HttpResponse
HttpResponse httpResponse = client.execute(mpost);
7、解析HttpResponse得到其中的数据
int code = httpResponse.getStatusLine().getStatusCode();
HttpEntity entity = httpResponse.getEntity();
InputStream inputStream = entity.getContent();
关于它们的简单封装
我们前面可以看到,每次发送一个请求都要写一大堆东西,这样不仅耗时,而且还不美观,代码比较臃肿,那么可不可以封装一下简单实用呢?答案是可以的,我们来实现一下
分析思路
1、请求之前,我们需要填写请求参数,但是每次写的都是一样的,所以,我们可以把这个参数填写改为一个方法,方便调用。
public static HttpParams GetMyParam(){
//Instantiation HttpParams
HttpParams params = new BasicHttpParams();
/**
* Set HttpClientConnection Params
*/
//Set ConnectionTimeOut
HttpConnectionParams.setConnectionTimeout(params,5000);
//Set SoTimeOut
HttpConnectionParams.setSoTimeout(params,5000);
//Set Tcp No Delay
HttpConnectionParams.setTcpNoDelay(params,true);
/**
* Set HttpClientProtocol Params
*/
//Set Http Version
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
//Set Http Charaset
HttpProtocolParams.setContentCharset(params,HTTP.UTF_8);
//Set Http keepAlive
HttpProtocolParams.setUseExpectContinue(params,true);
return params;
}
2、get和post中有相同的步骤,所以,我们新建几个常量表示请求方式
public static int GET = 1;
public static int POST = 2;
private int methed = 0;
public XhClient setMethod(int value){
methed = value;
return post;
}
post比较复杂,那么我们来对post进行分析,我们每次请求都需要初始化Client和HttpPost,这样太麻烦,我们可以这样写
public class XhClient {
private static HttpPost mpost;
static XhClient post = new XhClient();
public XhClient() {}
public static XhClient GetInstance(String url) {
mpost = new HttpPost(url);
mget = new HttpGet(url);
return post;
}
}
新建一个类用来封装我们的请求过程
3、在post中需要设置请求头,我们可以增加一个方法
public XhClient addHeader(String name, String value){
mpost.addHeader(name, value);
return post;
}
4、在post中还要设置请求参数,也可以写个方法
private List<NameValuePair> pairs = new ArrayList<>();
public XhClient addEntity(String name, String value){
pairs.add(new BasicNameValuePair(name, value));
return post;
}
5、最后我们需要执行请求并处理结果,我们知道,结果只有两种,成功或者失败,这其中的具体操作需要我们应用到具体的情景中,所以这里就去写一个接口来提供这两种方法
public interface NetInterface {
void Successed(InputStream inputStream);
void Failed(Integer code);
}
成功时我们得到流数据,失败时得到返回码,接口写好之后我们开始编写执行的方法
public void Compile(NetInterface netInterface){
HttpClient client = new DefaultHttpClient(GetMyParam());
int code = 0;
HttpResponse httpResponse = null;
try {
if(methed == XhClient.GET){
httpResponse = client.execute(mget);
code = httpResponse.getStatusLine().getStatusCode();
}else if(methed == XhClient.POST) {
mpost.setEntity(new UrlEncodedFormEntity(pairs));
httpResponse = client.execute(mpost);
code = httpResponse.getStatusLine().getStatusCode();
}
if (code == 200) {
HttpEntity entity = httpResponse.getEntity();
InputStream inputStream = entity.getContent();
netInterface.Successed(inputStream);
} else {
netInterface.Failed(code);
}
} catch (Exception e) {
e.printStackTrace();
netInterface.Failed(404);
}
}
这样,我们一个完整的封装类就完成了
public class XhClient {
public static int GET = 1;
public static int POST = 2;
private int methed = 0;
private List<NameValuePair> pairs = new ArrayList<>();
private static HttpPost mpost;
static XhClient post = new XhClient();
private static HttpGet mget;
public XhClient addEntity(String name, String value){
pairs.add(new BasicNameValuePair(name, value));
return post;
}
public XhClient addHeader(String name, String value){
mpost.addHeader(name, value);
return post;
}
public XhClient setMethod(int value){
methed = value;
return post;
}
public XhClient() {
}
public static XhClient GetInstance(String url) {
mpost = new HttpPost(url);
mget = new HttpGet(url);
return post;
}
public void Compile(NetInterface netInterface){
HttpClient client = new DefaultHttpClient(GetMyParam());
int code = 0;
HttpResponse httpResponse = null;
try {
if(methed == XhClient.GET){
httpResponse = client.execute(mget);
code = httpResponse.getStatusLine().getStatusCode();
}else if(methed == XhClient.POST) {
mpost.setEntity(new UrlEncodedFormEntity(pairs));
httpResponse = client.execute(mpost);
code = httpResponse.getStatusLine().getStatusCode();
}
if (code == 200) {
HttpEntity entity = httpResponse.getEntity();
InputStream inputStream = entity.getContent();
netInterface.Successed(inputStream);
} else {
netInterface.Failed(code);
}
} catch (Exception e) {
e.printStackTrace();
netInterface.Failed(404);
}
}
private HttpParams GetMyParam(){
//Instantiation HttpParams
HttpParams params = new BasicHttpParams();
/**
* Set HttpClientConnection Params
*/
//Set ConnectionTimeOut
HttpConnectionParams.setConnectionTimeout(params,5000);
//Set SoTimeOut
HttpConnectionParams.setSoTimeout(params,5000);
//Set Tcp No Delay
HttpConnectionParams.setTcpNoDelay(params,true);
/**
* Set HttpClientProtocol Params
*/
//Set Http Version
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
//Set Http Charaset
HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
//Set Http keepAlive
HttpProtocolParams.setUseExpectContinue(params,true);
return params;
}
public interface NetInterface {
void Successed(InputStream inputStream);
void Failed(Integer code);
}
}
使用方法
new Thread(new Runnable() {
@Override
public void run() {
Get();
}
}).start();
private void Get() {
XhClient client = XhClient.GetInstance("https://www.apiopen.top/meituApi?page=2")
.setMethod(XhClient.GET);
client.Compile(new XhClient.NetInterface() {
@Override
public void Successed(InputStream inputStream) {
String data = ToString.converStreamToString(inputStream);
}
@Override
public void Failed(Integer code) {
if (code == 404){
LogUtil.e("404");
}
}
});
}
private void Post(){
XhClient client = XhClient.GetInstance("https://www.apiopen.top/meituApi")
.setMethod(XhClient.POST)
.addEntity("page","1")
.addHeader("Connection", "Keep-Alive");
client.Compile(new XhClient.NetInterface() {
@Override
public void Successed(InputStream inputStream) {
String data = ToString.converStreamToString(inputStream);
}
@Override
public void Failed(Integer code) {
if (code == 404){
LogUtil.e("404");
}
}
});
}
这里我们用到了一个工具类
public class ToString {
static String converStreamToString(InputStream inputStream){
String data = null;
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder sb = new StringBuilder();
String line;
try {
while ((line = reader.readLine())!= null){
sb.append(line).append("\n");
}
data = sb.toString();
} catch (IOException e) {
e.printStackTrace();
LogUtil.e("converStreamToString Error");
}
return data;
}
}