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

HttpClient和HttpUrlConnection

2016-07-26 20:05 323 查看
HttpUrlConnection请求

// 创建url对象

URL url = new URL(urlStr);

// 打开链接

HttpURLConnection conn = (HttpURLConnection) url.openConnection();

// 设置链接超时时间为5秒

conn.setConnectTimeout(5000);

// 设置读取超时时间为5秒

conn.setReadTimeout(5000);

// 连接

conn.connect();

// 获取响应码200表示成功

int responseCode = conn.getResponseCode();

// 成功时的处理

if (200 == responseCode) {

// 获取输入流

InputStream is = conn.getInputStream();

//通过ByteArrayOutputStream类,把内容写到内存中

ByteArrayOutputStream bos = new ByteArrayOutputStream();

int len = -1;

byte[] buf = new byte[1024];

while ((len = is.read(buf)) != -1) {

//写到内存

bos.write(buf, 0, len);

}

//将byte数组转成utf-8字符串

final String text = bos.toString("utf-8");

//更新UI,使用runOnUiThread方法

runOnUiThread(new Runnable() {

public void run() {

//显示结果

mTv.setText(text);

}

});

}

HttpClick分为Post和get请求

可以用ByteArrayInputStream将字符串转换为输入流

HttpGet请求

// 首先创建httpGet对象,传入url地址

HttpGet get = new HttpGet(url);

// 创建一个client对象

HttpClient client = new DefaultHttpClient();

// 访问请求,并获取响应对象

HttpResponse resp = client.execute(get);

// 获取状态码

int statusCode = resp.getStatusLine().getStatusCode();

// 判断是否为200-成功

if (HttpStatus.SC_OK == statusCode) {

String content = EntityUtils.toString(resp.getEntity());

return content;

}

return "";

HttpPost请求

public static String readURLByPost(String url, String... params) throws Exception {

// 创建参数list

List<BasicNameValuePair> paramsList = new ArrayList<BasicNameValuePair>();

// 把所有参数添加到list中

for (int i = 0; i < params.length; i += 2) {

paramsList.add(new BasicNameValuePair(params[i], params[i + 1]));

}

HttpPost post = new HttpPost(url);

//设置实体参数

post.setEntity(new UrlEncodedFormEntity(paramsList,"utf-8"));

// 下面的跟get请求一样

// 创建一个client对象

HttpClient client = new DefaultHttpClient();

// 访问请求,并获取响应对象

HttpResponse resp = client.execute(post);

// 获取状态码

int statusCode = resp.getStatusLine().getStatusCode();

// 判断是否为200-成功

if (HttpStatus.SC_OK == statusCode) {

String content = EntityUtils.toString(resp.getEntity());

return content;

}

return "";

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