httpclientDemo

发布时间:2016-08-09 00:13:55   来源:文档文库   
字号:

package cn.itcast.httpclient;

import java.net.URI;

import org.apache.http.client.methods.CloseableHttpResponse;

import org.apache.http.client.methods.HttpGet;

import org.apache.http.client.utils.URIBuilder;

import org.apache.http.impl.client.CloseableHttpClient;

import org.apache.http.impl.client.HttpClients;

import org.apache.http.util.EntityUtils;

public class DoGETParam {

public static void main(String[] args) throws Exception {

// 创建Httpclient对象

CloseableHttpClient httpclient = HttpClients.createDefault();

// 定义请求的参数

URI uri = new URIBuilder("http://www.baidu.com/s").setParameter("wd", "java").build();

System.out.println(uri);

// 创建http GET请求

HttpGet httpGet = new HttpGet(uri);

CloseableHttpResponse response = null;

try {

// 执行请求

response = httpclient.execute(httpGet);

// 判断返回状态是否为200

if (response.getStatusLine().getStatusCode() == 200) {

String content = EntityUtils.toString(response.getEntity(), "UTF-8");

System.out.println(content);

}

} finally {

if (response != null) {

response.close();

}

httpclient.close();

}

}

}

//////////////////////////////////////////////////////////////

public class DoPOST {

public static void main(String[] args) throws Exception {

// 创建Httpclient对象

CloseableHttpClient httpclient = HttpClients.createDefault();

// 创建http POST请求

HttpPost httpPost = new HttpPost("http://www.oschina.net/");

httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36");

CloseableHttpResponse response = null;

try {

// 执行请求

response = httpclient.execute(httpPost);

// 判断返回状态是否为200

if (response.getStatusLine().getStatusCode() == 200) {

String content = EntityUtils.toString(response.getEntity(), "UTF-8");

System.out.println(content);

}

} finally {

if (response != null) {

response.close();

}

httpclient.close();

}

}

}

///////////////////////////////////////////////////////

本文来源:https://www.2haoxitong.net/k/doc/a32b3da2b1717fd5360cba1aa8114431b90d8e88.html

《httpclientDemo.doc》
将本文的Word文档下载到电脑,方便收藏和打印
推荐度:
点击下载文档

文档为doc格式