Java 模拟 HTTP 请求

Posted starudream

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java 模拟 HTTP 请求相关的知识,希望对你有一定的参考价值。

使用方法

HttpClient http://hc.apache.org/httpcomponents-client-ga/httpclient/dependency-info.html

// get
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet("http://targethost/homepage");
CloseableHttpResponse response1 = httpclient.execute(httpGet);
try {
    System.out.println(response1.getStatusLine());
    HttpEntity entity1 = response1.getEntity();
    EntityUtils.consume(entity1);
} finally {
    response1.close();
}

// post
HttpPost httpPost = new HttpPost("http://targethost/login");
List <NameValuePair> nvps = new ArrayList <NameValuePair>();
nvps.add(new BasicNameValuePair("username", "vip"));
nvps.add(new BasicNameValuePair("password", "secret"));
httpPost.setEntity(new UrlEncodedFormEntity(nvps));
CloseableHttpResponse response2 = httpclient.execute(httpPost);
try {
    System.out.println(response2.getStatusLine());
    HttpEntity entity2 = response2.getEntity();
    EntityUtils.consume(entity2);
} finally {
    response2.close();
}

简易的使用方式

fluent-hc http://hc.apache.org/httpcomponents-client-ga/fluent-hc/dependency-info.html

// get
Request.Get("http://targethost/homepage")
       .execute()
       .returnContent();

// post
Request.Post("http://targethost/login")
       .bodyForm(Form.form().add("username",  "vip").add("password",  "secret").build())
       .execute()
       .returnContent();

以上是关于Java 模拟 HTTP 请求的主要内容,如果未能解决你的问题,请参考以下文章

java 通过HTTP请求模拟登陆,获取不到cookie,高手帮忙看一下,代码如下

curl java 模拟http请求

java使用代理模拟http get请求

java模拟简易Http的get和post请求

java 客户端发起http请求2

Java模拟POST请求发送二进制数据