HttpClient--使用HttpClient进行Get Post请求访问
Posted iscys
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HttpClient--使用HttpClient进行Get Post请求访问相关的知识,希望对你有一定的参考价值。
在java后台开发中,我们有时候需要调用其他网站的接口进行数据的获取操作,我们一般会采用
1.java net 包中的URL 类,进行网络的数据获取
2.使用apache提供的HttpClient进行网络中数据的获取;
这里我们使用第二种方式,使用apache 提供的HttpClient进行数据的获取,接口的对接,下面附上HttpClientUtil 工具类,实现了POST与GET方法
package com.project.util; import java.io.IOException; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; public class HttpClientUtil { //使用HttpClient 进行doGET请求 public static String doGet(String url) { String result =null; //DefaultHttpClient httpclient =new DefaultHttpClient();//老版本的方法 CloseableHttpClient httpclient =HttpClients.createDefault(); HttpGet httpget =new HttpGet(url); try { HttpResponse response=httpclient.execute(httpget); HttpEntity entity=response.getEntity(); if(entity !=null) { result =EntityUtils.toString(entity,"UTF-8"); } } catch (Exception e) { e.printStackTrace(); } finally { try { if(httpclient !=null) { httpclient.close(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return result; } public static void main(String[] args) { String str=doGet("http://www.baidu.com"); System.out.println(str); } //使用HttpClient 进行dopOSTT请求,适合发送的数据为json数据格式 public static String doPOST(String url,String outstr) { //DefaultHttpClient httpclient =new DefaultHttpClient();//老版本的方法 CloseableHttpClient httpclient =HttpClients.createDefault(); HttpPost httppost =new HttpPost(url); String result =null; try { httppost.setEntity(new StringEntity(outstr, "UTF-8")); HttpResponse response=httpclient.execute(httppost); HttpEntity entity=response.getEntity(); if(entity !=null) { result =EntityUtils.toString(entity,"UTF-8"); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { if(httpclient !=null) { httpclient.close(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return result; } }
以上是关于HttpClient--使用HttpClient进行Get Post请求访问的主要内容,如果未能解决你的问题,请参考以下文章