天天看点

Java工具类--通过HttpClient发送http请求

在写网络程序的时候,经常会有从网址获取数据的需求,本文介绍一种Java发送http请求的工具–HttpClient。

HttpClient的介绍

      HttpClient最基本的功能就是执行http方法,执行http方法包括了一次或者几次HTTP请求和相应的变化,通常也是通过HttpClient来处理的。只要用户提供一个request的对象,HttpClient就会将用户的请求发送到目标服务器上,并且返回一个respone对象,如果没有执行成功将抛出一个异常。通过文档的介绍我们可以知道,发送HTTP请求一般可以分为以下步骤:

1.取得HttpClient对象
2.封装http请求
3.执行http请求
4.处理结果
           

  其中可以发送的请求类型有GET, HEAD, POST, PUT, DELETE, TRACE 和 OPTIONS

官方文档中的示例

//1.获得一个httpclient对象
CloseableHttpClient httpclient = HttpClients.createDefault();
//2.生成一个get请求
HttpGet httpget = new HttpGet("http://localhost/");
//3.执行get请求并返回结果
CloseableHttpResponse response = httpclient.execute(httpget);
try {
    //4.处理结果
} finally {
    response.close();
}
           

介绍一下最常用的HttpGet和HttpPost。 

RESTful提倡,通过HTTP请求对应的POST、GET、PUT、DELETE来完成对应的CRUD操作。 

所以本文介绍一下通过GET获取数据和POST提交数据的实现方法。

发送HttpGet

先介绍发送HttpGet请求

    /**
     * 发送HttpGet请求
     * @param url
     * @return
     */
    public static String sendGet(String url) {
        //1.获得一个httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        //2.生成一个get请求
        HttpGet httpget = new HttpGet(url);
        CloseableHttpResponse response = null;
        try {
            //3.执行get请求并返回结果
            response = httpclient.execute(httpget);
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        String result = null;
        try {
            //4.处理结果,这里将结果返回为字符串
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                result = EntityUtils.toString(entity);
            }
        } catch (ParseException | IOException e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }
           

发送HttpPost

发送HttpPost的方法和发送HttpGet很类似,只是将请求类型给位HttpPost即可。 

代码如下

/**
     * 发送不带参数的HttpPost请求
     * @param url
     * @return
     */
    public static String sendPost(String url) {
        //1.获得一个httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        //2.生成一个post请求
        HttpPost httppost = new HttpPost(url);
        CloseableHttpResponse response = null;
        try {
            //3.执行get请求并返回结果
            response = httpclient.execute(httppost);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //4.处理结果,这里将结果返回为字符串
        HttpEntity entity = response.getEntity();
        String result = null;
        try {
            result = EntityUtils.toString(entity);
        } catch (ParseException | IOException e) {
            e.printStackTrace();
        }
        return result;
    }
           

带参数的HttpPost,发送带参数的HttpPost

HttpClient通过UrlEncodedFormEntity,来提交带参数的请求

将需要提交的参数放在map里 

代码如下

  /**
     * 发送HttpPost请求,参数为map
     * @param url
     * @param map
     * @return
     */
    public static String sendPost(String url, Map<String, String> map) {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        List<NameValuePair> formparams = new ArrayList<NameValuePair>();
        for (Map.Entry<String, String> entry : map.entrySet()) {
            //给参数赋值
            formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }
        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);
        HttpPost httppost = new HttpPost(url);
        httppost.setEntity(entity);
        CloseableHttpResponse response = null;
        try {
            response = httpclient.execute(httppost);
        } catch (IOException e) {
            e.printStackTrace();
        }
        HttpEntity entity1 = response.getEntity();
        String result = null;
        try {
            result = EntityUtils.toString(entity1);
        } catch (ParseException | IOException e) {
            e.printStackTrace();
        }
        return result;
    }
           

完成代码如下,用到的jar包有httpclient-4.5.1.jar,httpcore-4.4.3.jar,

依赖的jar有commons-logging-1.2.jar 

注意是Apache HttpClient,不是commons-httpclient

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
/**
 * @author GWCheng
 *
 */
public class HttpUtil {

    private static final CloseableHttpClient httpclient = HttpClients.createDefault();

    /**
     * 发送HttpGet请求
     * @param url
     * @return
     */
    public static String sendGet(String url) {

        HttpGet httpget = new HttpGet(url);
        CloseableHttpResponse response = null;
        try {
            response = httpclient.execute(httpget);
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        String result = null;
        try {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                result = EntityUtils.toString(entity);
            }
        } catch (ParseException | IOException e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 发送HttpPost请求,参数为map
     * @param url
     * @param map
     * @return
     */
    public static String sendPost(String url, Map<String, String> map) {
        List<NameValuePair> formparams = new ArrayList<NameValuePair>();
        for (Map.Entry<String, String> entry : map.entrySet()) {
            formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }
        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);
        HttpPost httppost = new HttpPost(url);
        httppost.setEntity(entity);
        CloseableHttpResponse response = null;
        try {
            response = httpclient.execute(httppost);
        } catch (IOException e) {
            e.printStackTrace();
        }
        HttpEntity entity1 = response.getEntity();
        String result = null;
        try {
            result = EntityUtils.toString(entity1);
        } catch (ParseException | IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 发送不带参数的HttpPost请求
     * @param url
     * @return
     */
    public static String sendPost(String url) {
        HttpPost httppost = new HttpPost(url);
        CloseableHttpResponse response = null;
        try {
            response = httpclient.execute(httppost);
        } catch (IOException e) {
            e.printStackTrace();
        }
        HttpEntity entity = response.getEntity();
        String result = null;
        try {
            result = EntityUtils.toString(entity);
        } catch (ParseException | IOException e) {
            e.printStackTrace();
        }
        return result;
    }

}
           

测试用例

服务器端代码

@Controller
@RequestMapping("/test")
// /test/**
public class TestController {
    // /test/view post 提交数据,模拟表单
    @RequestMapping(value = "/view", method = RequestMethod.POST)
    public void viewTest(PrintWriter out, HttpServletResponse response, @RequestParam("param1") String param1,
            @RequestParam("param2") String param2) {
        response.setContentType("application/json;charset=UTF-8");
        Gson gson = new GsonBuilder().create();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("param1", param1);
        map.put("param2", param2);
        System.out.println(gson.toJson(map));
        out.print(gson.toJson(map));
    }

    // /test/view?param1=aaa&param2=bbb get 
        @RequestMapping(value = "/view", method = RequestMethod.GET)
        public void viewTest3(PrintWriter out, HttpServletResponse response, @RequestParam("param1") String param1,
                @RequestParam("param2") String param2) {
            response.setContentType("application/json;charset=UTF-8");
            Gson gson = new GsonBuilder().create();
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("param1", param1);
            map.put("param2", param2);
            System.out.println(gson.toJson(map));
            out.print(gson.toJson(map));
        }

    // /test/view2/{courseId}
    @RequestMapping(value = "/view2/{param}", method = RequestMethod.GET)
    public void viewTest1(PrintWriter out, HttpServletResponse response, @PathVariable("param") String param) {
        response.setContentType("application/json;charset=UTF-8");
        Gson gson = new GsonBuilder().create();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("param", param);
        out.print(gson.toJson(map));
    }

    // /test/view3
    @RequestMapping(value = "/view3", method = RequestMethod.POST)
    public void viewTest2(PrintWriter out, HttpServletResponse response) {
        response.setContentType("application/json;charset=UTF-8");
        Gson gson = new GsonBuilder().create();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("status", "success");
        out.print(gson.toJson(map));
    }

}
           

测试代码

public class HttpClientTest {

    @Test
    public void testGet() {
        //百度天气的api
        //String url1 = "http://api.map.baidu.com/telematics/v3/weather?location=%E5%8C%97%E4%BA%AC&output=json&ak=W69oaDTCfuGwzNwmtVvgWfGH";
        String url1 = "http://localhost:8080/wechat/test/view2/你好世界";
        String result1 = HttpUtil.sendGet(url1);
        System.out.println(result1);
        //输出{"param":"你好世界"}
    }
    @Test
    public void testPost() throws UnsupportedEncodingException{
        String url = "http://localhost:8080/wechat/test/view";
        Map<String,String> map = new HashMap<String,String>();
        map.put("param1", "你好世界");
        map.put("param2", "哈哈");
        String result = HttpUtil.sendPost(url, map);
        System.out.println(result);
        //输出结果{"param1":"你好世界","param2":"哈哈"}

    }

    @Test
    public void testPost1() throws UnsupportedEncodingException{
        String url = "http://localhost:8080/wechat/test/view3";
        String result = HttpUtil.sendPost(url);
        System.out.println(result);
        //输出结果{"status":"success"}

    }

}
           

建议通过HttpGet获取信息,HttpPost提交信息,

而HttpGet获取信息时需要提交的参数一般会在url中体现,

或者以?传参,或者在url中传参,所以就没写HttpGet带参数的。

也希望大家能遵循Http的设计原则,通过HttpGet, HttpPost, HttpPut, HttpDelete,

来实现获取数据,提交数据,修改数据,和删除数据的方法。

---------------------

本文来自 GW_Cheng 的CSDN 博客 ,全文地址请点击:https://blog.csdn.net/frankcheng5143/article/details/50070591

继续阅读