使用java发送HTTP请求

近来在写项目时调用第三方接口,发现使用第三方接口基本都要使用java程序来发送HTTP请求到第三方的服务器去获取数据,不同的第三方提供的方法不尽相同,有使用org.apache.commons.httpclient的,有使用org.apache.http.client的,有使用org.codehaus.xfire.client,还有使用org.springframework.web.client的,个人还是比较喜欢使用java原生的java.net.URL与java.net.HttpURLConnection来发送HTTP请求,所以自己写了一个方法,共飨诸君

public static String sendHttpRequest(String url, String entity, String method) {
    BufferedReader bufferedReader = null;
    URL realUrl;
    HttpURLConnection conn = null;
    PrintWriter printWriter = null;
    String result = "";
    try {
        if ("get".equals(method)) {
            if (entity != null && !"".equals(entity)) {
                realUrl = new URL(url + "?" + entity);
            } else {
                realUrl = new URL(url);
            }
            // 根据url生成urlConnection对象
            conn = (HttpURLConnection) realUrl.openConnection();
           /* conn.connect();可以不明文设定连接,conn.getInputStream()会自动连接*/
        } else if ("post".equals(method)) {
            realUrl = new URL(url);
            conn = (HttpURLConnection) realUrl.openConnection();
            conn.setRequestMethod("POST");/*设定请求的方法为"POST",默认是GET */
            if (entity != null && !"".equals(entity)) {
                // 设置是否从httpUrlConnection读入,默认情况下是true;
                conn.setDoInput(true);
                /*设置是否向httpUrlConnection输出,因为这个是post请求,参数要放在 http正文内,因此需要设为true, 默认情况下是false*/
                conn.setDoOutput(true);
                // Post 请求不能使用缓存
                conn.setUseCaches(false);
                conn.connect();
                printWriter = new PrintWriter(conn.getOutputStream());
                printWriter.print(entity);
                printWriter.flush();
            }
        }else{
            throw new IllegalArgumentException("请输入正确的请求方式");
        }
        bufferedReader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line;
        if ((line = bufferedReader.readLine()) != null) {
            result += line;
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (printWriter != null) {
                printWriter.close();
            }
            if (bufferedReader != null) {
                bufferedReader.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return result;
    }

}
测试方法如下:<特意测试了post请求,请求参数为null的情况>

public static void main(String[] args) {
    String str = "userMobile=15539266567&usertype=0";
    System.out.println(sendHttpRequest("http://localhost:8080/mine/try", null, "get"));
    System.out.println(sendHttpRequest("http://localhost:8080/mine/your/best", str, "post"));
    System.out.println(sendHttpRequest("http://localhost:8080/mine/so/amazing", null, "post"));
}
在控制台打印输出,哈哈,是不是很完美。关于PUT请求与DELETE请求与POST请求类似,不再敖述。

false
1
{"StageCategory":[{"id":"001","name":"第一阶段"},{"id":"002","name":"第二阶段"},{"id":"003","name":


Java的世界里,HttpClient 是一个功能强大的Http请求库,然而接口非常复杂,设计上遵从正交性,简单的请求也需要写比较多的代码,更不要说隐藏在各种细节里面的高级用法了。Requests,  是一个模仿python requests 模块来设计的Http lib,拥有简单而灵活的API,在容易使用的同时,又能够满足各种高级定制的使用,可是说是当前最好用的Java Http Client Lib。 简单的请求示例:String url = ...; Response resp = Requests.get(url).text(); // post 和其他方法 resp = Requests.post(url).text(); resp = Requests.head(url).text(); //读取Http Response  int statusCode = resp.getStatusCode(); Headers headers = resp.getHeaders(); Cookies cookies = resp.getCookies(); String body = resp.getBody(); //response 返回其他类型 resp = Requests.get(url).text("UTF-8"); // get response as bytes Response resp1 = Requests.get(url).bytes(); // save response as file  Response resp2 = Requests.get(url).file("/path/to/save/file"); // url 参数: Map map = new HashMap(); map.put("k1", "v1"); map.put("k2", "v2"); Response resp = Requests.get(url).param("key1", "value1").params(map)         //.params(new Parameter(...), new Parameter(...))         .text(); // 请求头 Response resp = Requests.get(url).header("key1", "value1").headers(map)         //.headers(new Header(...), new Header(...))         .text(); // 添加Cookie: Map cookies = new HashMap(); Response resp = Requests.get(url).cookie("key1", "value1").cookies(map)         //.cookies(new Cookie(...), new Cookie(...))         .text(); //  设置 userAgent Response resp = Requests.get(url).userAgent(userAgent).text(); // 增加请求数据(post, put, patch方法) // send form-encoded data. x-www-form-urlencoded header will be send automatically Response resp = Requests.post(url).data(map).text(); // send string data String str = ...; resp = Requests.post(url).data(str, "UTF-8").text(); // send from inputStream InputStream in = ... resp = Requests.post(url).data(in).text(); // multipart 请求, 用于文件上传: Response resp = Requests.post(url).data(map).multiPart("ufile", "/path/to/file")         .multiPart(..., ...).text();请求设置://禁止自动重定向
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值