HttpURLConnection&HttpClient网络通信

时间:2022-10-04 04:04:35

一:HttpURLConnection简介:

  用于发送或者接受HTTP协议请求的类,获得的数据可以是任意类型和长度,这个类可以用于发送和接收流数据,其长度事先不知道。

  使用这个类遵循一下模式:

  1. 获得一个新的HttpURLConnection通过调用URL.openConnection()获得一个HttpURLConnection实例
  2. 准备请求。请求的主要特性是它的URI。请求头也可以包括元数据,如凭证,首选的内容类型和会话cookie。
  3. 可选择上传请求主体。实例必须配置 setDoOutput(true),如果他们有一个请求主体。以书面形式向被返回的流的getOutputStream.
  4. 读取响应。响应头通常包括元数据,如响应主体的内容类型和长度,修改日期和会话Cookie。响应体可以从返回的流中的getInputStream。如果响应没有主体,该方法返回一个空流。
  5. 断开。一旦响应体已被读取时,HttpURLConnection的应该调用关闭disconnect()。断开释放一个连接持有的资源,所以他们可能被关闭或重新使用。

如下:是通过HttpURLConnection或的数据的例子:

网址url =  new URL ( "http://www.android.com/" );
HttpURLConnection urlConnection = ( HttpURLConnection ) url . openConnection ();
try {
InputStream in = new BufferedInputStream ( urlConnection . getInputStream ());
readStream ( in );
finally {
urlConnection . disconnect ();
}

  HttpURLConnection详细功能,请参照谷歌官方API:http://developer.android.com/reference/java/net/HttpURLConnection.html

  HttpClient简介:

  接口的HTTP客户端。HTTP客户端封装执行HTTP请求,同时处理Cookie,认证,连接管理等功能所需对象的大杂烩。HTTP客户端的线程安全依赖于特定的客户端的实现和配置。

  该类不建议在API22上使用。

  常用的公共方法有:

  1:execute(HttpUriRequest request);     执行使用默认情况下的请求.

  2: getConnectionManager();                获得使用该客户端的连接管理器。

  3: getParams();                                  获得参数,这个用于客户端。

HttpClient这个类比较简单,详细的信息可以参照谷歌官方API:  http://developer.android.com/reference/org/apache/http/client/HttpClient.html

二:通过一个简单的Demo来分别实现HttpURLConnection和HttpClient的GET和POST请求。

  1:Demo展示如下,非常简单:

HttpURLConnection&HttpClient网络通信

  2:Activity中代码实现如下:

  (注:因为HTTP网络请求是耗时操作,所以在android开发中,为避免耗时操作阻塞主线程,

   需使用子线程或这一步操作实现这些耗时操作。本例中使用的是AsyncTast异步处理。)

 package activity.cyq.httplearn;

 import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView; import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils; import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List; public class MainActivity extends AppCompatActivity implements View.OnClickListener { private Button HTTP_GET, HTTP_POST, HTTPClinet_GET, HTTPClient_P0st;
private TextView dataShow;
private final String urlStr = "http://apis.juhe.cn/mobile/get?phone=13429667914&key=a26da09113eaf8bd24456f0bd4037eb3";
private final String urlPost = "http://apis.juhe.cn/mobile/get";
private String phone = "1342966";/*手机号码前七位*/
private final String key = "a26da09113eaf8bd24456f0bd4037eb3"; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); HTTP_GET = (Button) findViewById(R.id.HTTP_GetBTN);
HTTP_POST = (Button) findViewById(R.id.HTTP_PostBTN);
HTTPClinet_GET = (Button) findViewById(R.id.HTTPClient_GetBTN);
HTTPClient_P0st = (Button) findViewById(R.id.HTTPClient_PostBTN);
dataShow = (TextView) findViewById(R.id.dataShowText); HTTP_GET.setOnClickListener(this);
HTTP_POST.setOnClickListener(this);
HTTPClinet_GET.setOnClickListener(this);
HTTPClient_P0st.setOnClickListener(this); } @Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.HTTP_GetBTN:
new AsyncTask<String, Void, String>() {
@Override
protected String doInBackground(String... params) {
try {
URL url = new URL(params[0]);
URLConnection connection = url.openConnection();
InputStream is = connection.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
StringBuilder sBuilder = new StringBuilder();
while ((line = br.readLine()) != null) {
sBuilder.append(line);
}
br.close();
isr.close();
is.close();
return "HTTP_GET请求方式数据结果:" + sBuilder.toString(); } catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
} @Override
protected void onPostExecute(String s) {
dataShow.append(s);
super.onPostExecute(s);
}
}.execute(urlStr);
break;
case R.id.HTTP_PostBTN:
new AsyncTask<String, Void, String>() {
@Override
protected String doInBackground(String... params) {
URL url = null;
try {
url = new URL(params[0]);
HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST");
connection.setReadTimeout(8000);
connection.setConnectTimeout(1000); OutputStream os = connection.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
bw.write("phone=13429667914&key=a26da09113eaf8bd24456f0bd4037eb3");
bw.close();
osw.close();
os.close(); InputStream is = connection.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
StringBuilder sBuilder = new StringBuilder();
while ((line = br.readLine()) != null) {
sBuilder.append(line);
}
br.close();
isr.close();
is.close();
return "HTTP_POST请求方式数据结果:" + sBuilder.toString(); } catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
} @Override
protected void onPostExecute(String s) {
dataShow.append(s);
super.onPostExecute(s);
}
}.execute(urlStr);
break;
case R.id.HTTPClient_GetBTN:
new AsyncTask<String, Void, String>() {
@Override
protected String doInBackground(String... params) { HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(params[0]);
try {
HttpResponse response = client.execute(get);
if (response.getStatusLine().getStatusCode() == 200) {
String result = EntityUtils.toString(response.getEntity());
return result;
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
} @Override
protected void onPostExecute(String s) {
dataShow.append("HTTPClient_Get请求方式数据结果:" + s);
super.onPostExecute(s);
} }.execute(urlStr);
break;
case R.id.HTTPClient_PostBTN:
new AsyncTask<String, Void, String>() {
@Override
protected String doInBackground(String... params) { int photoStr = Integer.parseInt(params[1]);
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(params[0]);
List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();
list.add(new BasicNameValuePair("phone", "13429667914"));
list.add(new BasicNameValuePair("key", "a26da09113eaf8bd24456f0bd4037eb3")); try {
post.setEntity(new UrlEncodedFormEntity(list));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} try {
HttpResponse response = client.execute(post);
if (response.getStatusLine().getStatusCode() == 200) {
String result = EntityUtils.toString(response.getEntity());
return result;
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
} @Override
protected void onPostExecute(String s) {
dataShow.append("HTTPClient_POST请求方式数据结果:" + s);
super.onPostExecute(s);
}
}.execute(urlPost, phone, key);
break; } }
}