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();

猜你喜欢

转载自www.cnblogs.com/StarUDream/p/9045555.html