您的位置:首页 > 理论基础 > 计算机网络

使用HttpClient方式请求网络

2015-08-05 17:49 399 查看
Android中有两种基于Http的网络访问对象,一种是Java自带的HttpURLConnection,另一种是HttpClient。但是新版本的Android SDK中将不再支持HttpClient。

实现步骤:

1. 定义一个HttpClient客户端对象

2. 定义方法,如HttpGet,HttpPost

3. 使用客户端执行定义的方法,返回HttpResponse响应对象

4. 使用响应对象,获得状态码,处理内容

/**GET方式进行访问
*
* @param userName
* @param password
* @return
*/
public static String loginOfGet(String userName, String password) {
HttpClient client = null;
try {
client = new DefaultHttpClient();
//定义一个get请求方法
String data = "username=" + userName + "&password=" + password;
HttpGet get = new HttpGet("......." + data);

//设置请求头消息
//post.addHeader("Content-Length", "20");

//服务器相应对象,其中包含了状态信息和服务器返回的数据
HttpResponse response = client.execute(get); //开始执行get方法,请求网络

//获得响应码
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
InputStream is = response.getEntity().getContent();
String text = getStringFromInputStream(is);
return text;
} else {
Log.i(TAG, "请求失败" + statusCode);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (client != null) {
client.getConnectionManager().shutdown(); //关闭连接,释放资源
}
}
return null;

}


/**POST方式进行访问
*
* @param userName
* @param password
* @return
*/
public static String loginOfPost(String userName, String password) {
HttpClient client = null;
try {
//1.定义一个客户端
client = new DefaultHttpClient();

//2.定义post方法
HttpPost post = new HttpPost(".......");

List<NameValuePair> parameters = new ArrayList<NameValuePair>();
parameters.add(new BasicNameValuePair("username", userName));
parameters.add(new BasicNameValuePair("password", password));
//把post请求的参数包装了一层
//不写编码名称,服务器收取数据时乱码。需要指定字符集为utf-8
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters, "utf-8");
//设置参数
post.setEntity(entity);

//设置请求头消息
//post.addHeader("Content-Length", "20"); //...........

//3.使用客户端执行post方法
HttpResponse response = client.execute(post);

//4.使用响应对象,获得状态码,处理内容
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
//使用响应对象获得实体,获得输入流
InputStream is = response.getEntity().getContent();
String text = getStringFromInputStream(is);
return text;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (client != null) {
client.getConnectionManager().shutdown(); //关闭连接,释放资源
}
}
return null;
}


/**
* 根据流返回一个字符串信息
* @param is
* @return
* @throws IOException
*/
private static String getStringFromInputStream(InputStream is) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream(); //定义缓存流
byte[] buffer = new byte[1024]; //定义一个字节数组
int len = -1;
while((len = is.read(buffer))!= -1) { //如果没有结束,执行写入操作
baos.write(buffer, 0, len);
}
is.close();

//String html = baos.toString(); //把流中的数据转换成字符串,采用编码:utf-8

String html = new String(baos.toByteArray(), "GBK");
baos.close();

return html;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: