Android 如何使用Http协议访问网络
Android使用Http协议访问网络主要有两种方式,一个是使用 java.net.*(标准Java接口),另一个是使用 Org.apache接口。
java.net.*:中是可以认为是JDK中的java网络处理包,提供了流,Socket,网络协议等常见网络相关类。
Apache HttpClient:是一个开源项目,功能相对与JDK中的更加完善,可以为客户端提供高效丰富的Http编程支持
一:使用java.net包来进行Http协议的网络编程
public class CustomHttpURLConnection {
private static String TAG = "CustomHttpUrlConnection";
//代表 客户端与服务器之间的一个Http连接
private static HttpURLConnection conn;
public CustomHttpURLConnection() {
}
/**
* 向服务器发送Get请求
* @param strUrl 发送Get请求的url地址
* @param nameValuePairs get请求参数
* @return
*/
public static String GetFromWebByHttpUrlConnection(String strUrl,
NameValuePair... nameValuePairs) {
String result="";
try {
//1.新建Url对象
URL url = new URL(strUrl);
//2.获取并设置HttpURLConnection对象
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setConnectTimeout(3000);
conn.setReadTimeout(4000);
conn.setRequestProperty("accept", "*/*");
//3.连接服务器
conn.connect();
//4.从建立好的连接中获取inputStream
InputStream stream=conn.getInputStream();
//5.为了更好的读取inputStream中的数据,包装inputStream
InputStreamReader inReader=new InputStreamReader(stream);
BufferedReader buffer=new BufferedReader(inReader);
//6.开始读取数据
String strLine=null;
while((strLine=buffer.readLine())!=null)
{
result+=strLine;
}
//7.关闭出入流
inReader.close();
//8.关闭连接
conn.disconnect();
return result;
} catch (MalformedURLException e) {
Log.e(TAG, "getFromWebByHttpUrlCOnnection:"+e.getMessage());
e.printStackTrace();
return null;
} catch (IOException e) {
Log.e(TAG, "getFromWebByHttpUrlCOnnection:"+e.getMessage());
e.printStackTrace();
return null;
}
}
/**
* 向服务器发送Post请求
* @param strUrl
* @param nameValuePairs
* @return
*/
public static String PostFromWebByHttpURLConnection(String strUrl,
NameValuePair... nameValuePairs) {
String result="";
try {
URL url = new URL(strUrl);
conn = (HttpURLConnection) url
.openConnection();
// 设置是否从httpUrlConnection读入,默认情况下是true;
conn.setDoInput(true);
// 设置是否向httpUrlConnection输出,因为这个是post请求,参数要放在
// http正文内,因此需要设为true, 默认情况下是false;
conn.setDoOutput(true);
// 设定请求的方法为"POST",默认是GET
conn.setRequestMethod("POST");
//设置超时
conn.setConnectTimeout(3000);
conn.setReadTimeout(4000);
// Post 请求不能使用缓存
conn.setUseCaches(false);
conn.setInstanceFollowRedirects(true);
// 设定传送的内容类型是可序列化的java对象
// (如果不设此项,在传送序列化对象时,当WEB服务默认的不是这种类型时可能抛java.io.EOFException)
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
// 连接,从上述第2条中url.openConnection()至此的配置必须要在connect之前完成,
conn.connect();
InputStream in = conn.getInputStream();
InputStreamReader inStream=new InputStreamReader(in);
BufferedReader buffer=new BufferedReader(inStream);
String strLine=null;
while((strLine=buffer.readLine())!=null)
{
result+=strLine;
}
return result;
} catch (IOException ex) {
Log.e(TAG,"PostFromWebByHttpURLConnection:"+ ex.getMessage());
ex.printStackTrace();
return null;
}
}
}
二:使用Apache HttpClient
public class CustomHttpClient {
private static String TAG = "CustomHttpClient";
private static final CommonLog log = LogFactory.createLog();
private static final String CHARSET_UTF8 = HTTP.UTF_8;
private static final String CHARSET_GB2312 = "GB2312";
private static HttpClient customerHttpClient;
private CustomHttpClient() {
}
/**
* HttpClient post方法
*
* @param url
* @param nameValuePairs
* @return
*/
public static String PostFromWebByHttpClient(Context context, String url,
NameValuePair... nameValuePairs) {
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
if (nameValuePairs != null) {
for (int i = 0; i < nameValuePairs.length; i++) {
params.add(nameValuePairs[i]);
}
}
UrlEncodedFormEntity urlEncoded = new UrlEncodedFormEntity(params,
CHARSET_UTF8);
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(urlEncoded);
HttpClient client = getHttpClient(context);
HttpResponse response = client.execute(httpPost);
if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
throw new RuntimeException("请求失败");
}
HttpEntity resEntity = response.getEntity();
return (resEntity == null) ? null : EntityUtils.toString(resEntity,
CHARSET_UTF8);
} catch (UnsupportedEncodingException e) {
Log.w(TAG, e.getMessage());
return null;
} catch (ClientProtocolException e) {
Log.w(TAG, e.getMessage());
return null;
} catch (IOException e) {
throw new RuntimeException(context.getResources().getString(
R.string.httpError), e);
}
}
public static String getFromWebByHttpClient(Context context, String url,
NameValuePair... nameValuePairs) throws Exception{
log.d("getFromWebByHttpClient url = " + url);
try {
// http地址
// String httpUrl =
// "http://192.168.1.110:8080/httpget.jsp?par=HttpClient_android_Get";
StringBuilder sb = new StringBuilder();
sb.append(url);
if (nameValuePairs != null && nameValuePairs.length > 0) {
sb.append("?");
for (int i = 0; i < nameValuePairs.length; i++) {
if (i > 0) {
sb.append("&");
}
sb.append(String.format("%s=%s",
nameValuePairs[i].getName(),
nameValuePairs[i].getValue()));
}
}
// HttpGet连接对象
HttpGet httpRequest = new HttpGet(sb.toString());
// 取得HttpClient对象
HttpClient httpclient = getHttpClient(context);
// 请求HttpClient,取得HttpResponse
HttpResponse httpResponse = httpclient.execute(httpRequest);
// 请求成功
if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
throw new RuntimeException(context.getResources().getString(
R.string.httpError));
}
return EntityUtils.toString(httpResponse.getEntity());
} catch (ParseException e) {
// TODO Auto-generated catch block
throw new RuntimeException(context.getResources().getString(
R.string.httpError),e);
} catch (IOException e) {
// TODO Auto-generated catch block
log.e("IOException ");
e.printStackTrace();
throw new RuntimeException(context.getResources().getString(
R.string.httpError),e);
}
}
/**
* 创建httpClient实例
*
* @return
* @throws Exception
*/
private static synchronized HttpClient getHttpClient(Context context) {
if (null == customerHttpClient) {
HttpParams params = new BasicHttpParams();
// 设置一些基本参数
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, CHARSET_UTF8);
HttpProtocolParams.setUseExpectContinue(params, true);
HttpProtocolParams
.setUserAgent(
params,
"Mozilla/5.0(Linux;U;Android 2.2.1;en-us;Nexus One Build.FRG83) "
+ "AppleWebKit/553.1(KHTML,like Gecko) Version/4.0 Mobile Safari/533.1");
// 超时设置
/* 从连接池中取连接的超时时间 */
ConnManagerParams.setTimeout(params, 1000);
/* 连接超时 */
int ConnectionTimeOut = 3000;
if (!HttpUtils.isWifiDataEnable(context)) {
ConnectionTimeOut = 10000;
}
HttpConnectionParams
.setConnectionTimeout(params, ConnectionTimeOut);
/* 请求超时 */
HttpConnectionParams.setSoTimeout(params, 4000);
// 设置我们的HttpClient支持HTTP和HTTPS两种模式
SchemeRegistry schReg = new SchemeRegistry();
schReg.register(new Scheme("http", PlainSocketFactory
.getSocketFactory(), 80));
schReg.register(new Scheme("https", SSLSocketFactory
.getSocketFactory(), 443));
// 使用线程安全的连接管理来创建HttpClient
ClientConnectionManager conMgr = new ThreadSafeClientConnManager(
params, schReg);
customerHttpClient = new DefaultHttpClient(conMgr, params);
}
return customerHttpClient;
}
}
Android网络访问详解
1023

被折叠的 条评论
为什么被折叠?



