在 java 后台开发中, 我们有时候需要调用其他网站的接口进行数据的获取操作, 我们一般会采用
1.java net 包中的 URL 类, 进行网络的数据获取
这里我们使用第二种方式, 使用 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 请求访问
来源: http://www.bubuko.com/infodetail-2734508.html