在android项目中,经常需要用到网络,而在联网之前前,我们都要做一次网络的判断,判断当前的网络状态是否可用,然后开始请求网络。
android中请求网络方式有:HttpURLConnection和HttpClient:
第一种方式:HttpURLConnection
/**
* 使用HttpURLConnection请求Internet
* @param context context对象
* @param isNeedProxy 是否需要代理
* @param requestUrl 请求的URL
* @param param 请求的参数
* @return 返回一个inputstream流
*/
public static InputStream getHttpURLConnectionInputStream(Context context,boolean isNeedProxy,String requestUrl,Map<String, String> param) {
URL url;
HttpURLConnection conn = null;
InputStream input = null;
try {
url = new URL(requestUrl);
if(isNeedProxy) //当请求的网络为需要使用代理时
{
Proxy proxy = new Proxy(java.net.Proxy.Type.HTTP,new InetSocketAddress("192.168.1.23", 80));
conn = (HttpURLConnection) url.openConnection(proxy);
}else{
conn = url.openConnection();
}
conn.setConnectTimeout(10000); //请求超时
conn.setRequestMethod("POST"); //请求方式
conn.setReadTimeout(1000); //读取超时
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestProperty("Charset", "UTF-8");
conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
OutputStream os = conn.getOutputStream();
StringBuilder sb = new StringBuilder();
Iterator<String> it = param.keySet().iterator();
while (it.hasNext()) {
String key = it.next();
String value = param.get(key);
sb.append(key).append("=").append(value).append("&");
}
String p = sb.toString().substring(0, sb.length()-1);
os.write(p.getBytes("utf-8"));
os.close();
if(conn!=null)
{
input = conn.getInputStream();
}
} catch (Exception e) {
e.printStackTrace();
}
return input;
}
上面这种方式就是HttpURLConnection ,这种方式在android开发中也是比较常用的。
第二种方式:HttpClient
/**
* 使用HttpURLConnection请求Internet
* @param context context对象
* @param isNeedProxy 是否需要代理
* @param requestUrl 请求的URL
* @param param 请求的参数
* @return 返回一个inputstream流
*/
public static InputStream getHttpClientInputStream(Context context,boolean isNeedProxy,String requestUrl, Map<String, String> param)throws Exception {
HttpClient client = new DefaultHttpClient();
if(isNeedProxy) //当请求的网络为需要使用代理时
{
HttpHost proxy = new HttpHost("192.168.1.23", 80);
client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,
proxy);
}
HttpPost hp = new HttpPost(requestUrl);
hp.setHeader("Charset", "UTF-8");
hp.setHeader("Content-Type", "application/x-www-form-urlencoded");
List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();
Iterator<String> it = param.keySet().iterator();
while (it.hasNext()) {
String key = it.next();
list.add(new BasicNameValuePair(key, param.get(key)));
}
hp.setEntity(new UrlEncodedFormEntity(list,"UTF-8"));
HttpResponse response = null;
response = client.execute(hp);
return response.getEntity().getContent();
}
注意:这里的response.getEntity().getContent()只能使用一次,如果调用了多次会抛异常:java.lang.IllegalStateException: Content has been consumed
HttpClient通常比HttpURLConnection要好用些。