Java之HttpClient的常规用法
需要的jar包下载地址
点击下载
http://download.csdn.net/download/weixin_39549656/10272781
用处
1.HttpClient可以读取网页(HTTP/HTTPS)内容
2.对url发送get/post请求(带不带参数都可以),对项目进行测试
代码
post请求
package baike;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
public class Test {
public static void main(String[] args) throws IOException {
HttpClient client = HttpClients.createDefault();// 创建默认http连接
HttpPost post = new HttpPost("http://127.0.0.1/dispatch/accessResult");// 创建一个post请求
List<NameValuePair> paramList = new ArrayList<NameValuePair>();
paramList.add(new BasicNameValuePair("carNO", "京C004"));//传递的参数
// 把参转码后放入请求实体中
HttpEntity entitya = new UrlEncodedFormEntity(paramList, "utf-8");
post.setEntity(entitya);// 把请求实体放post请求中
HttpResponse response = client.execute(post);// 用http连接去执行get请求并且获得http响应
HttpEntity entity = response.getEntity();// 从response中取到响实体
String html = EntityUtils.toString(entity);// 把响应实体转成文本
System.out.println(html);
}
}
get请求
package baike;
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class Test {
public static void main(String[] args) throws IOException {
HttpClient client = HttpClients.createDefault();// 创建默认http连接
HttpGet get = new HttpGet("http://127.0.0.1/dispatch/accessResult");// 创建一个post请求
HttpResponse response = client.execute(get);// 用http连接去执行get请求并且获得http响应
HttpEntity entity = response.getEntity();// 从response中取到响实体
String html = EntityUtils.toString(entity);// 把响应实体转成文本
System.out.println(html);
}
}
转换字符集
HttpClient client = HttpClients.createDefault();// 创建默认http连接
HttpPost post = new HttpPost("http://www.qiubaichengren.net/miss/8162.html");// 创建一个get请求
HttpResponse response = client.execute(post);// 用http连接去执行get请求并且获得http响应
HttpEntity entity = response.getEntity();// 从response中取到响实体
String string2 = EntityUtils.toString(entity, "GBK");
System.out.println(string2);