技术成长之路

网络编程(二)

2017-03-03  本文已影响0人  逍遥的魂儿假不正经吧

Apache的HttpClient和Java的HttpURLConnection:

自己封装的网络请求类,第三方的网络请求框架都离不开的两个类库

1.HttpClient:

Android6.0版本直接删除了HttpClient类库,采用了OKHttp。

1⃣️简要说一下HttpClient的GET请求:

(1).创建HttpClient

private HttpClient createHttpClient() {

HttpParams mDefaultHttpParams =newBasicHttpParams();

//设置连接超时

HttpConnectionParams.setConnectionTimeout(mDefaultHttpParams,15000);

HttpConnectionParams.setTcpNoDelay(mDefaultHttpParams,true);

HttpProtocolParams.setVersion(mDefaultHttpParams, HttpVersion.HTTP_1_1);

HttpProtocolParams.setContentCharset(mDefaultHttpParams, HTTP.UTF_8);

//持续握手

HttpProtocolParams.setUseExpectContinue(mDefaultHttpParams,true);

HttpClient mHttpClient=newDefaultHttpClient(mDefaultHttpParams);

returnmHttpClient;

(2).接下来创建HttpGet和HttpClient,请求网络并得到HttpResponse,并对HttpResponse进行处理:

private void useHttpClientGet(String url) {

HttpGet mHttpGet =newHttpGet(url);

mHttpGet.addHeader("Connection","Keep-Alive");

try{

HttpClient mHttpClient = createHttpClient();

HttpResponse mHttpResponse = mHttpClient.execute(mHttpGet);

HttpEntity mHttpEntity = mHttpResponse.getEntity();

intcode =mHttpResponse.getStatusLine().getStatusCode();

if(null!= mHttpEntity) {

InputStream mInputStream =mHttpEntity.getContent();

String respose =converStreamToString(mInputStream);

Log.i("wangshu","请求状态码:"+ code +"\n请求结果:\n"+ respose);

mInputStream.close();

}

}catch(IOException e) {

e.printStackTrace();

}

(3).converStreamToString方法将请求结果转换成String类型:

private String converStreamToString(InputStream is) throws IOException {

BufferedReader reader = new BufferedReader(new InputStreamReader(is));

StringBuffer sb = new StringBuffer();

String line = null;

while ((line = reader.readLine()) != null) {

sb.append(line + "\n");

}

String respose = sb.toString();

return respose;

}

(4).最后我们开启线程访问百度:

new Thread(new Runnable() {

@Override

public void run() {

useHttpClientGet("http://www.baidu.com");

}

}).start();

返回结果:

返回结果

2⃣️.HttpClient的POST请求:

private void useHttpClientPost(String url) {

HttpPost mHttpPost = new HttpPost(url);       

mHttpPost.addHeader("Connection", "Keep-Alive");       

try {           

HttpClient mHttpClient = createHttpClient();         

  ListpostParams = new ArrayList<>();

//要传递的参数

postParams.add(new BasicNameValuePair("username", "moon"));

postParams.add(new BasicNameValuePair("password", "123"));

mHttpPost.setEntity(new UrlEncodedFormEntity(postParams));

HttpResponse mHttpResponse = mHttpClient.execute(mHttpPost);

HttpEntity mHttpEntity = mHttpResponse.getEntity();

int code = mHttpResponse.getStatusLine().getStatusCode();

if (null != mHttpEntity) {

InputStream mInputStream = mHttpEntity.getContent();

String respose = converStreamToString(mInputStream);

Log.i("wangshu", "请求状态码:" + code + "\n请求结果:\n" + respose);

mInputStream.close();

}

} catch (IOException e) {

e.printStackTrace();

}}

2.HttpURLConnection:

在Android 6.0版本中,HttpClient库被移除了,HttpURLConnection则是以后我们唯一的选择。

HttpURLConnection的POST请求:

会了HttpURLConnection的POST请求那GET请求也就会了,所以我这里只举出POST的例子:

(1).首先我们创建一个UrlConnManager类,然后里面提供getHttpURLConnection()方法用于配置默认的参数并返回HttpURLConnection:

public static HttpURLConnection getHttpURLConnection(String url){

HttpURLConnection mHttpURLConnection=null;

try {

URL mUrl=new URL(url);

mHttpURLConnection=(HttpURLConnection)mUrl.openConnection();

//设置链接超时时间

mHttpURLConnection.setConnectTimeout(15000);

//设置读取超时时间

mHttpURLConnection.setReadTimeout(15000);

//设置请求参数

mHttpURLConnection.setRequestMethod("POST");

//添加Header

mHttpURLConnection.setRequestProperty("Connection","Keep-Alive");

//接收输入流

mHttpURLConnection.setDoInput(true);

//传递参数时需要开启

mHttpURLConnection.setDoOutput(true);

} catch (IOException e) {

e.printStackTrace();

}

return mHttpURLConnection ;

}

(2).因为我们要发送POST请求,所以在UrlConnManager类中再写一个postParams()方法用来组织一下请求参数并将请求参数写入到输出流中:

public static void postParams(OutputStream output,Listparams List) throws IOException{

StringBuilder mStringBuilder=new StringBuilder();

for (NameValuePair pair:paramsList){

if(!TextUtils.isEmpty(mStringBuilder)){

mStringBuilder.append("&");

}

mStringBuilder.append(URLEncoder.encode(pair.getName(),"UTF-8"));

mStringBuilder.append("=");

mStringBuilder.append(URLEncoder.encode(pair.getValue(),"UTF-8"));

}

BufferedWriter writer=new BufferedWriter(new OutputStreamWriter(output,"UTF-8"));

writer.write(mStringBuilder.toString());

writer.flush();

writer.close();

}

(3).接下来我们添加请求参数,调用postParams()方法将请求的参数组织好传给HttpURLConnection的输出流,请求连接并处理返回的结果:

private void useHttpUrlConnectionPost(String url) {                                                     InputStream mInputStream = null;                                                                       HttpURLConnection mHttpURLConnection = UrlConnManager.getHttpURLConnection(url);        try {                                                                                                                                                    List postParams = new ArrayList<>();

//要传递的参数

postParams.add(new BasicNameValuePair("username", "moon"));

postParams.add(new BasicNameValuePair("password", "123"));

UrlConnManager.postParams(mHttpURLConnection.getOutputStream(), postParams);

mHttpURLConnection.connect();

mInputStream = mHttpURLConnection.getInputStream();

int code = mHttpURLConnection.getResponseCode();

String respose = converStreamToString(mInputStream);

Log.i("buxq", "请求状态码:" + code + "\n请求结果:\n" + respose);

mInputStream.close();

} catch (IOException e) {

e.printStackTrace();

}

}

(4).最后开启线程请求网络:

private void useHttpUrlConnectionGetThread() {

new Thread(new Runnable() {

@Override

public void run() {

useHttpUrlConnectionPost("http://www.baidu.com");

}

}).start();

}

上一篇下一篇

猜你喜欢

热点阅读