Java调用第三方http接口的4种方式:restTemplate,HttpURLConnection,HttpClient,hutool的HttpUtil,实例直接干,以防忘记

Java调用第三方http接口的方式:
1restTemplate,
2HttpURLConnection,
3HttpClient,
4hutool的HttpUtil


        <dependency>
            <groupId>commons-httpclientgroupId>
            <artifactId>commons-httpclientartifactId>
            <version>3.1version>
        dependency>

        <dependency>
            <groupId>cn.hutoolgroupId>
            <artifactId>hutool-allartifactId>
            <version>5.4.1version>
        dependency>

直接干代码实例,这是一个controller,放在自己的springboot项目里,直接启动
用postman测试
Java调用第三方http接口的4种方式:restTemplate,HttpURLConnection,HttpClient,hutool的HttpUtil,实例直接干,以防忘记_第1张图片

package com.example.dfademo.control;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.example.dfademo.pojos.DfaItem;
import com.example.dfademo.pojos.ResponseResult;
import com.example.dfademo.util.HttpClientToInterface;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
public class TestController {
    @PostMapping("/test")
    public ResponseResult test(@RequestBody DfaItem dfaItem){
        return ResponseResult.okResult(dfaItem);
    }
	//restTemplate
    @PostMapping("/send")
    public void send(@RequestBody DfaItem dfaItem){
        RestTemplate restTemplate = new RestTemplate();
        //创建请求头
        HttpHeaders httpHeaders = new HttpHeaders();
        //参数
        Map<String, Object> query = new HashMap<>();
        query.put("dfaId", "123");
        query.put("dfaName", "test");
        HttpEntity<Map<String, Object>> httpEntity = new HttpEntity<>(httpHeaders);
        String url = "http://localhost:8080/test";
        //请求地址、请求体以及返回参数类型
        ResponseResult responseResult = restTemplate.postForObject(url, query, ResponseResult.class);
        System.out.println("123");
    }
	//HttpURLConnection
    @PostMapping("/send2")
    public void send2(@RequestBody DfaItem dfaItem) throws Exception {
        OutputStreamWriter out = null;
        BufferedReader br = null;
        String result = "";
        // 创建URL对象
        URL url = new URL("http://localhost:8080/test");
        // 打开连接
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        try {
            // 设置请求方法为POST
            connection.setRequestMethod("POST");
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
            connection.setRequestProperty("Content-Type", "application/json;charset=utf-8");
            connection.setDoOutput(true);
            connection.setDoInput(true);
            // 获取输入流
            OutputStream outputStream = connection.getOutputStream();
            // 构造要传递的JSON字符串
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("dfaId","123");
            jsonObject.put("dfaName","qwe");
            String jsonBody = jsonObject.toJSONString();
            // 将JSON写入输入流中
            byte[] input = jsonBody.getBytes("utf-8");
            outputStream.write(input, 0, input.length);
            outputStream.close();
            // 获取服务器返回结果
            int responseCode = connection.getResponseCode();
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            StringBuilder stringBuilder = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line).append("\n");
            }
            reader.close();
            System.out.println("Response Code : " + responseCode);
            System.out.println("Server Response : \n" + stringBuilder.toString());
        } finally {
            // 关闭连接
            connection.disconnect();
        }
    }
    //HttpClient
    @PostMapping("/send3")
    public void send3(@RequestBody DfaItem dfaItem){
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("dfaId","123");
        jsonObject.put("dfaName","qwe");
        String s = HttpClientToInterface.doPost("http://localhost:8080/test", jsonObject);
        System.out.println("");
    }
    //hutool的HttpUtil
    @PostMapping("/send4")
    public void send4(@RequestBody DfaItem dfaItem){
        // url:放请求地址
        String url = "http://localhost:8080/test";
        HttpRequest request = HttpUtil.createPost(url);
        Map<String, String> headers = new HashMap<>();
        // 头部传参,根据接口写传参名,和值
        String authorization = "";
        headers.put("Authorization", authorization);
        request.addHeaders(headers);

        // 封装参数,对象转json
        String body = JSONUtil.toJsonStr(dfaItem);

        // 发送请求
        String infoStr = request.body(body).timeout(1000).execute().body();

        // 获取返回参数某个字段
        String errorCode = (String) JSONUtil.parseObj(infoStr).get("errcode");
        // 获取的数据转成对象
        DfaItem keywordVO = JSONUtil.toBean(infoStr, DfaItem.class);
        System.out.println("123");
    }




}

package com.example.dfademo.pojos;

import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.Date;

import static com.baomidou.mybatisplus.annotation.IdType.ASSIGN_ID;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class DfaItem {
    @TableId(type = ASSIGN_ID)
    private Long dfaId;
    private String dfaName;
    private String createBy;
    @TableField(fill = FieldFill.INSERT)
    private Date createTime;
    @TableField(fill = FieldFill.INSERT_UPDATE)
    private Date updateTime;
}

package com.example.dfademo.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;

import java.io.IOException;
import java.io.InputStream;
public class HttpClientToInterface {
 
    /**
     * httpClient的get请求方式
     * 使用GetMethod来访问一个URL对应的网页实现步骤:
     * 1.生成一个HttpClient对象并设置相应的参数;
     * 2.生成一个GetMethod对象并设置响应的参数;
     * 3.用HttpClient生成的对象来执行GetMethod生成的Get方法;
     * 4.处理响应状态码;
     * 5.若响应正常,处理HTTP响应内容;
     * 6.释放连接。
     * @param url
     * @param charset
     * @return
     */
    public static String doGet(String url, String charset){
        /**
         * 1.生成HttpClient对象并设置参数
         */
        HttpClient httpClient = new HttpClient();
        //设置Http连接超时为5秒
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
 
        /**
         * 2.生成GetMethod对象并设置参数
         */
        GetMethod getMethod = new GetMethod(url);
        //设置get请求超时为5秒
        getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 5000);
        //设置请求重试处理,用的是默认的重试处理:请求三次
        getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
 
        String response = "";
 
        /**
         * 3.执行HTTP GET 请求
         */
        try {
            int statusCode = httpClient.executeMethod(getMethod);
 
            /**
             * 4.判断访问的状态码
             */
            if (statusCode != HttpStatus.SC_OK){
                System.err.println("请求出错:" + getMethod.getStatusLine());
            }
 
            /**
             * 5.处理HTTP响应内容
             */
            //HTTP响应头部信息,这里简单打印
            Header[] headers = getMethod.getResponseHeaders();
            for (Header h: headers){
                System.out.println(h.getName() + "---------------" + h.getValue());
            }
            //读取HTTP响应内容,这里简单打印网页内容
            //读取为字节数组
            byte[] responseBody = getMethod.getResponseBody();
            response = new String(responseBody, charset);
            System.out.println("-----------response:" + response);
            //读取为InputStream,在网页内容数据量大时候推荐使用
            //InputStream response = getMethod.getResponseBodyAsStream();
 
        } catch (HttpException e) {
            //发生致命的异常,可能是协议不对或者返回的内容有问题
            System.out.println("请检查输入的URL!");
            e.printStackTrace();
        } catch (IOException e){
            //发生网络异常
            System.out.println("发生网络异常!");
        }finally {
            /**
             * 6.释放连接
             */
            getMethod.releaseConnection();
        }
        return response;
    }
 
    /**
     * post请求
     * @param url
     * @param json
     * @return
     */
    public static String doPost(String url, JSONObject json){
        HttpClient httpClient = new HttpClient();
        PostMethod postMethod = new PostMethod(url);
 
        postMethod.addRequestHeader("accept", "*/*");
        postMethod.addRequestHeader("connection", "Keep-Alive");
        //设置json格式传送
        postMethod.addRequestHeader("Content-Type", "application/json;charset=utf-8");
        //必须设置下面这个Header
        postMethod.addRequestHeader("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
        //添加请求参数
        postMethod.setRequestBody(json.toJSONString());

        String res = "";
        try {
            int code = httpClient.executeMethod(postMethod);
            if (code == 200){
                res = postMethod.getResponseBodyAsString();
                System.out.println(res);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return res;
    }
 
    public static void main(String[] args) {
        doGet("http://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=13026194071", "UTF-8");
 
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("commentId", "13026194071");
        doPost("http://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=13026194071", jsonObject);
    }
}

你可能感兴趣的:(java,工具,java,http,lua)