java发送http get 和 post 请求

来源:互联网 发布:网络舆情分析系统 编辑:程序博客网 时间:2022/08/11 16:04

原生的纯java发送书写起来很麻烦,所以推荐apache的HttpClient和HttpCore包,里面已经封装好了一系列的接口。

1.get

<pre name="code" class="java">public class HttpGetTest {
public static void main(String[] args) throws IOException{
<span style="white-space:pre"></span>//直接将参数写在网址中并请求这个网址
<span style="white-space:pre"></span>String url = "https://www.baidu.com/s?ie=UTF-8&wd=%E7%99%BE%E5%BA%A6";
<span style="white-space:pre"></span>//旧的方法如HttpClient client = new DefaultHttpClient();已经被弃用,现在用该静态方法来创建clientCloseableHttpClient httpClient = HttpClients.createDefault();HttpGet httpget = new HttpGet(url);CloseableHttpResponse response = httpClient.execute(httpget);if(response.getStatusLine().getStatusCode() == 200){
<span style="white-space:pre"></span>//获取返回的值String result = EntityUtils.toString(response.getEntity());System.out.println(result);}}}

2.post


public class HttpPostTest {public static void main(String[] args) throws IOException{
<span style="white-space:pre"></span>String url = "https://www.baidu.com";CloseableHttpClient httpClient = HttpClients.createDefault();
<span style="white-space:pre"></span>//使用包装好的类来设置post的参数List<NameValuePair> formparams = new ArrayList<NameValuePair>();formparams.add(new BasicNameValuePair("q", "www.douban.com/note site:www.douban.com"));UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);HttpPost httppost = new HttpPost(url);
<span style="white-space:pre"></span>httppost.setEntity(entity);
CloseableHttpResponse response = httpClient.execute(httppost);System.out.println(response.getStatusLine().getStatusCode());if(response.getStatusLine().getStatusCode() == 200){String result = EntityUtils.toString(response.getEntity());System.out.println(result);}
<span style="white-space:pre"></span>//关闭资源
<span style="font-family: Arial, Helvetica, sans-serif;"></span>EntityUtils.consume(entity);<span style="font-family: Arial, Helvetica, sans-serif;"></span>
}}

3.总结

可以看出post仅仅比get多出了一些添加参数的工作,其他的方面都大致差不多。
在官网上还给出了更简洁的例子,但是我没有进行测试,放上来仅供大家参考。

The same requests can be executed using a simpler, albeit less flexible, fluent API.
// The fluent API relieves the user from having to deal with manual deallocation of system// resources at the cost of having to buffer response content in memory in some cases.Request.Get("http://targethost/homepage")    .execute().returnContent();Request.Post("http://targethost/login")    .bodyForm(Form.form().add("username",  "vip").add("password",  "secret").build())    .execute().returnContent();

在正常的请求过程中,需要使用try-catch-finally来关闭掉response以释放资源,在这里我为了代码更加简单就没有进行相应的操作,但是强烈建议关闭不必要的链接。
在程序运行的过程中需要注意的是,可能会报java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory的错误,主要是因为缺少commons-logging jar包,导入commons-logging.jar即可。
最后附上下载地址:
HttpClient及HttpCore:http://hc.apache.org/downloads.cgi
commons-logging.jar:点击打开链接

0 0