URLConnection和HttpURLConnection使用的都是java.net中的类,属于标准的java接口。
HttpURLConnection继承自URLConnection,差别在与HttpURLConnection仅仅针对Http连接。
访问网络实例
public class MainActivity extends ActionBarActivity {
private Button btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final String urlStr = "http://www.baidu.com";
btn = (Button) findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
new AsyncTask<String, Void, String>() {
@Override
protected String doInBackground(String... arg0) {
return doGet(arg0[0]);
// return doPost(arg0[0]);
}
}.execute(urlStr);
}
});
}
// 通过默认的GET方式获取数据
public String doGet(String urlStr) {
StringBuilder sb = new StringBuilder();
try {
URL url = new URL(urlStr);
URLConnection con = url.openConnection();
con.setConnectTimeout(6 * 1000);// 设置超时
if (((HttpURLConnection) con).getResponseCode() != 200)
throw new RuntimeException("请求url失败");
// 创建读取流
InputStream is = con.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line = "";
// 循环读取数据
while ((line = br.readLine()) != null) {
sb.append(line);
}
// 关闭流
br.close();
isr.close();
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
// 通过POST方式获取数据
public String doPost(String urlStr) {
StringBuilder sb = new StringBuilder();
try {
URL url = new URL(urlStr);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
// 设置请求方法和输出数据
con.setDoOutput(true);
con.setRequestMethod("POST");
con.setConnectTimeout(6 * 1000);// 设置超时
if (con.getResponseCode() != 200)
throw new RuntimeException("请求url失败");
// 添加参数
OutputStreamWriter osw = new OutputStreamWriter(
con.getOutputStream(), "utf-8");
BufferedWriter bw = new BufferedWriter(osw);
bw.write("userId=1");
bw.flush();
// 读取返回的数据
InputStream is = con.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line = "";
// 循环读取数据
while ((line = br.readLine()) != null) {
sb.append(line);
}
// 关闭流
br.close();
isr.close();
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
}
HttpURLConnection与HttpClient
在 JDK 的 java.net 包中已经提供了访问 HTTP 协议的基本功能:HttpURLConnection。但是对于大部分应用程序来说,JDK 库本身提供的功能还不够丰富和灵活。 在Android中,androidSDK中集成了Apache的HttpClient模块,用来提供高效的、最新的、功能丰富的支持 HTTP 协议工具包,并且它支持 HTTP 协议最新的版本和建议。使用HttpClient可以快速开发出功能强大的Http程序。
两者区别:
HttpClient是个很不错的开源框架,封装了访问http的请求头,参数,内容体,响应等等, HttpURLConnection是java的标准类,什么都没封装,用起来太原始,不方便,比如重访问的自定义,以及一些高级功能等。
public class MainActivity extends Activity {
private Button btn;
private HttpClient client;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
client = new DefaultHttpClient();
btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
String url = "http://www.baidu.com";
doGet(url);
}
});
}
// 通过HttpGet来访问网络
public void doGet(String url) {
new AsyncTask<String, Void, Void>() {
@Override
protected Void doInBackground(String... arg0) {
String urlStr = arg0[0];
HttpGet get = new HttpGet(urlStr);
try {
// 发送请求方法并返回
HttpResponse response = client.execute(get);
// 获取数据
String value = EntityUtils.toString(response.getEntity());
System.out.println(value);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}.execute(url);
}
// 通过HttpPost来访问网络
public void doPost(String url) {
new AsyncTask<String, Void, Void>() {
@Override
protected Void doInBackground(String... arg0) {
String urlStr = arg0[0];
HttpPost post = new HttpPost(urlStr);
try {
// 附加参数
List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();
list.add(new BasicNameValuePair("userId", "1"));
post.setEntity(new UrlEncodedFormEntity(list));
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
try {
// 发送请求方法并返回
HttpResponse response = client.execute(post);
// 获取数据
String value = EntityUtils.toString(response.getEntity());
System.out.println(value);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}.execute(url);
}
}