使用HttpURLConnection 和HttpClient

1.使用HttpURLConnection 需要new出一个URL对象然后调用openConnection()

URL url = new URL("http://www.baidu.com");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();

得到HttpURLConnection 实例之后我们可以设置一下HTTP请求所使用的方法。GET和POST

connection.setRequestMethod("GET");

设置连接超时时间

connection.setConnectTimeout(8000);
connection.setReadTimeout(8000);

之后调用getInputStream()获取服务器返回的输入流

InputStream in = connection.getInputStream();

最后调用disconnect() 方法将HTTP连接关掉

connection.disconnect();


private Handler handler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case SHOW_RESPONSE:
String response = (String) msg.obj;
// 在这里进行UI操作,将结果显示到界面上
responseText.setText(response);
}
}
};
private void sendRequestWithHttpURLConnection() {
// 开启线程来发起网络请求
new Thread(new Runnable() {
@Override
public void run() {
HttpURLConnection connection = null;
try {
URL url = new URL("http://www.baidu.com");
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(8000);
connection.setReadTimeout(8000);
InputStream in = connection.getInputStream();
// 下面对获取到的输入流进行读取
BufferedReader reader = new BufferedReader(new
InputStreamReader(in));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
Message message = new Message();
message.what = 0;
// 将服务器返回的结果存放到Message中
message.obj = response.toString();
handler.sendMessage(message);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
}).start();
}
如果是想要提交数据给服务器,,只需要将HTTP 请求
的方法改成POST,并在获取输入流之前把要提交的数据写出即可。注意每条数据都要以键
值对的形式存在,数据与数据之间用&符号隔开

connection.setRequestMethod("POST");
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
out.writeBytes("username=admin&password=123456");

2.使用HttpClient

它可以完成和HttpURLConnection 几乎一模一样的效果,但两者之间的用法却有较
大的差别,HttpClient 是一个接口,因此无法创建它的实例,通常情况下都会创
建一个DefaultHttpClient 的实例

HttpClient httpClient = new DefaultHttpClient();

如果想要发起一条GET 请求,就可以创建一个HttpGet 对象

HttpGet httpGet = new HttpGet("http://www.baidu.com");
httpClient.execute(httpGet);

如果是发起一条POST 请求会比GET 稍微复杂一点,我们需要创建一个HttpPost 对象,
并传入目标的网络地址

HttpPost httpPost = new HttpPost("http://www.baidu.com");
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", "admin"));
params.add(new BasicNameValuePair("password", "123456"));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, "utf-8");
httpPost.setEntity(entity);
httpClient.execute(httpPost);
如果返回码等于200 说明请求成功了

if (httpResponse.getStatusLine().getStatusCode() == 200) {
// 请求和响应都成功了
}

调用getEntity()方法获取到一个HttpEntity :

HttpEntity entity = httpResponse.getEntity();

String response = EntityUtils.toString(entity);

中文

String response = EntityUtils.toString(entity, "utf-8");

private void sendRequestWithHttpClient() {
new Thread(new Runnable() {
@Override
public void run() {
try {
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://www.baidu.com");
HttpResponse httpResponse = httpClient.execute(httpGet);
if (httpResponse.getStatusLine().getStatusCode() == 200) {
// 请求和响应都成功了
HttpEntity entity = httpResponse.getEntity();
String response = EntityUtils.toString(entity,
"utf-8");
Message message = new Message();
message.what = 0;
// 将服务器返回的结果存放到Message中
message.obj = response.toString();
handler.sendMessage(message);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值