代码中有介绍到两种发起网络访问方式:HttpClient HttpURLConnection
还有两种请求方式:GET POST
还用了两种实现方法:Thread+Handler AsyncTask
例子简单明白,代码注释也很多,就不用过多介绍了
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpConnection;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
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.conn.params.ConnManagerParams;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
public class MainActivity extends Activity {
final int INTERNET_REQUEST = 100;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String url = "http://www.baidu.com";
new My_Thread(url).start();
new asynctask().execute(url);
}
Handler handler = new Handler() {
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case INTERNET_REQUEST:
System.out.println("hand :" + msg.obj.toString());
break;
default:
break;
}
}
};
/**
* HttpClient访问网络 HttpGet请求
*/
public String InternetRequest_1(String url) {
String result = "";
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 3000); // 设置连接超时
HttpConnectionParams.setSoTimeout(client.getParams(), 3000); // 设置数据读取时间超时
ConnManagerParams.setTimeout(client.getParams(), 3000); // 设置从连接池中取连接超时
HttpGet get = new HttpGet(url);
try {
HttpResponse response = client.execute(get);// 执行访问并获得返回码
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { // 响应通过
result = EntityUtils.toString(response.getEntity(), "UTF-8");
}// 注意做异常处理
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
/**
* HttpClient访问网络 HttpPost请求
*/
public String InternetRequest_2(String url) {
String result = "";
HttpClient client = new DefaultHttpClient(); // 新建HttpClient对象
HttpPost post = new HttpPost(url); // 新建HttpPost对象
List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>(); // 使用NameValuePair来保存要传递的Post参数
params.add(new BasicNameValuePair("username", "hello")); // 添加要传递的参数
params.add(new BasicNameValuePair("password", "eoe"));
HttpEntity entity;
try {
entity = new UrlEncodedFormEntity(params, HTTP.UTF_8);
post.setEntity(entity); // 设置参数实体
HttpResponse response = client.execute(post); // 获取HttpResponse实例
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { // 响应通过
result = EntityUtils.toString(response.getEntity(), "UTF-8");
} else {
// 响应未通过
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
/**
* HttpURLConnection访问网络 HttpGet请求
*/
public String InternetRequest_3(String url) {
StringBuffer strbu = new StringBuffer();
try {
URL URL = new URL(url);
String line = "";
HttpURLConnection connection = (HttpURLConnection) URL
.openConnection();
connection.setReadTimeout(5000);
connection.setRequestMethod("GET");
BufferedReader in = new BufferedReader(new InputStreamReader(
connection.getInputStream(), "utf-8"));
while ((line = in.readLine()) != null) {
strbu.append(line);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return strbu.toString();
}
/**
* HttpURLConnection访问网络 HttpPost请求
*/
public String InternetRequest_4(String url) {
StringBuffer strbu = new StringBuffer();
String params;
try {
params = "username=" + URLEncoder.encode("hello", "UTF-8")
+ "&password=" + URLEncoder.encode("eoe", "UTF-8");
byte[] postData = params.getBytes();
URL pathUrl = new URL(url); // 创建一个URL对象
HttpURLConnection connect = (HttpURLConnection) pathUrl
.openConnection();
connect.setConnectTimeout(3000); // 设置连接超时时间
connect.setDoOutput(true); // post请求必须设置允许输出
connect.setUseCaches(false); // post请求才能使用缓存
connect.setRequestMethod("POST"); // 设置post方式请求
connect.setInstanceFollowRedirects(true);
connect.setRequestProperty("Content-Type",
"application/x-www-form-urlencode");// 配置请求Content-Type
connect.connect(); // 开始连接
DataOutputStream dos = new DataOutputStream(
connect.getOutputStream()); // 发送请求参数
dos.write(postData);
dos.flush();
dos.close();
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(connect.getInputStream()));
String line;
if (connect.getResponseCode() == 200) { // 请求成功
// 定义BufferedReader输入流来读取URL的ResponseData
while ((line = bufferedReader.readLine()) != null) {
strbu.append("/n").append(line);
}
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return strbu.toString();
}
/**
* 通过异步任务的方式访问网络
*/
class asynctask extends AsyncTask<String, Void, String> {
protected String doInBackground(String... params) {
String url=params[0];
String result = InternetRequest_1(url);
// String result = InternetRequest_2(url);
// String result = InternetRequest_3(url);
// String result = InternetRequest_4(url);
return result;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// 对result进行操作
}
}
/**
* 通过Thread+Hanlder的方式安全访问网络 光用Thread不安全 在Hanlder里面根据对用标识符得到对应的数据进行操作
*/
class My_Thread extends Thread {
private String url;
public My_Thread(String url) {
this.url=url;
}
public void run() {
super.run();
String result = InternetRequest_1(url);
// String result = InternetRequest_2(url);
// String result = InternetRequest_3(url);
// String result = InternetRequest_4(url);
Message mes = new Message();
mes.obj = result;// 要传输的内容,可以为任何对象
mes.what = INTERNET_REQUEST;// 用于标识从哪个地方发出去的和上面的result一一对应
handler.sendMessage(mes);
}
}
}