码迷,mamicode.com
首页 > 编程语言 > 详细

Java 模拟 HTTP 请求

时间:2018-05-16 15:19:13      阅读:201      评论:0      收藏:0      [点我收藏+]

标签:asi   page   方法   nal   new   try   enc   htm   ret   

使用方法

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 请求

标签:asi   page   方法   nal   new   try   enc   htm   ret   

原文地址:https://www.cnblogs.com/StarUDream/p/9045555.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!