java三种发送http请求的方式 resttemplete httpclient apache-common-http

一、Resttemplete

resttemplete通用方法exchange

1.先在maven引入依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--用到了JSONObject ,引入fastjson依赖-->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.70</version>
</dependency>

2.方法

public String getCookie() throws IOException {
		//paramMap:请求体
        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("bodyKey","bodyValue");
        //headers:请求头 import的时候选择springframework不要选择其他的
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type","application/json");
        headers.add("headerKey","headerValue");
        //url:请求地址
        String url = "www.abc.com";
        String response = sendHttpPost(url,JSONObject.toJSONString(paramMap),headers);
        return response;
    }

    private String sendHttpPost(String url,String param, HttpHeaders headers) throws IOException {
    //将请求头和请求体都塞入HttpEntity,用来做exchange的参数
        HttpEntity requestEntity = new HttpEntity(param,headers);
        //发送请求,HttpMethod.POST代表POST请求,可更换为其他,如GET
        ResponseEntity<String> response = restTemplate.exchange(url,HttpMethod.POST,requestEntity, String.class);
        //此处获取了响应头中的set-cookie字段(注意:获取出来的不只包括value,而是key+value)
        //也可以getHeader获取响应头
        //		getBody:获取响应体
        List<String> response = response.getHeaders().get("set-cookie");
        return response.getBody;
    }

二、java原生的net

1.发送http请求

private String sendConnHttpPut(String url ,Map<String, Object> param) throws IOException {
		//param:请求体Map
        String requestBody = JSONObject.toJSONString(param);
        String sign = null;
        StringBuilder httpsPost = new StringBuilder();
        try {
            URL url3 = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) url3.openConnection();
            //设置超时时间 毫秒为单位 可忽略
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(5000);
            //设置请求方式
            conn.setRequestMethod("POST");
            //设置请求头
            conn.setRequestProperty("Content-Type", "application/json;charset=utf-8"); 
            conn.setDoOutput(true);
            conn.setDoInput(true);
            OutputStream outputStream = conn.getOutputStream();
            outputStream.write(requestBody.getBytes(StandardCharsets.UTF_8));
            //获取URLConnection对象对应的输入流
            InputStream is = conn.getInputStream();
            //构造一个字符流缓存
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String str = "";

            while ((str = br.readLine()) != null) {
                httpsPost.append(str);
            }
            //关闭流
            is.close();
            conn.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
        //返回
        return httpsPost.toString();
    }

三、apache.commons.httpclient

1.先在maven引入依赖

<dependency>
    <groupId>commons-httpclient</groupId>
    <artifactId>commons-httpclient</artifactId>
    <version>3.1</version>
</dependency>

2.方法

public String getHttpCookie() throws IOException {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("params", "params");
        String url = "www.abc.com";
        return sendPost(JSONObject.toJSONString(paramMap), url);
    }
    public String sendPost(String params, String requestUrl) throws IOException {
        byte[] requestBytes = params.getBytes(StandardCharsets.UTF_8); // 将参数转为二进制流
        HttpClient httpClient = new HttpClient();// 客户端实例化
        PostMethod postMethod = new PostMethod(requestUrl);
        // 设置请求头  Content-Type
        postMethod.setRequestHeader("Content-Type", "application/json");
        InputStream inputStream = new ByteArrayInputStream(requestBytes, 0,
                requestBytes.length);
        RequestEntity requestEntity = new InputStreamRequestEntity(inputStream, requestBytes.length, "application/json; charset=utf-8"); // 请求体
        //塞请求头和请求体
        postMethod.setRequestEntity(requestEntity);
        httpClient.executeMethod(postMethod);// 执行请求
        StringBuilder response = new StringBuilder("");
        BufferedReader br = null;
        try {
        //获取请求体  获取其他的可以修改此地方
            InputStream is = putMethod.getResponseBodyAsStream();
            br = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
            String str = "";
            while ((str = br.readLine()) != null) {
                response.append(str);
            }
        } catch (Exception e) {
            System.out.println(e);
        } finally {
            if (br != null) {
                br.close();
            }
        }
        return response.toString();
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值