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

32 篇文章 0 订阅

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

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

        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.4.1</version>
        </dependency>

直接干代码实例,这是一个controller,放在自己的springboot项目里,直接启动
用postman测试
在这里插入图片描述

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);
    }
}

  • 10
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
好的,可以的,以下是使用HttpURLConnection调用第三方WebService接口的基本步骤: 1. 创建URL对象,设置目标WebService地址。 2. 使用URL对象创建HttpURLConnection对象。 3. 设置HttpURLConnection对象的请求方法为POST。 4. 设置HttpURLConnection对象的连接超时时间和读取超时时间。 5. 设置HttpURLConnection对象的请求头信息。 6. 设置HttpURLConnection对象的请求体信息。 7. 发送请求,获取响应。 8. 解析响应,获取需要的数据。 具体实现细节可以参考以下示例代码,供您参考: ``` URL url = new URL("http://xxxxxx:8080/xxxxx/xxxxx");//WebService地址 HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST");//请求方式为POST conn.setConnectTimeout(5000);//连接超时时间为5秒 conn.setReadTimeout(5000);//读取超时时间为5秒 conn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");//设置请求头信息 String soapXml = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ser=\"http://service.xxx.com/\">" + "<soapenv:Header/>" + "<soapenv:Body>" + "<ser:xxxxx>" + "<ser:xxxxx>xxxxx</ser:xxxxx>" + "<ser:xxxxx>xxxxx</ser:xxxxx>" + "</ser:xxxxx>" + "</soapenv:Body>" + "</soapenv:Envelope>"; conn.setRequestProperty("Content-Length", String.valueOf(soapXml.getBytes().length));//设置请求体长度 conn.setDoOutput(true);//设置允许输出 OutputStream os = conn.getOutputStream(); os.write(soapXml.getBytes());//写入请求体信息 os.flush(); os.close(); if (conn.getResponseCode() == 200) {//获取响应码 InputStream is = conn.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8")); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line); } is.close(); reader.close(); String result = sb.toString();//获取响应数据 //解析响应数据,获取需要的数据 } else { //请求失败处理逻辑 } conn.disconnect();//关闭连接 ``` 需要注意的是,以上示例代码中的SOAP请求体格式是一常见的WebService请求格式,如果需要调用其他格式的WebService接口,请求体格式可能会有所不同。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

谷咕咕

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值