调用其他项目接口的几种方式

1 篇文章 0 订阅

一、通过HttpClient的方式

package com.zoey.http.utils;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.net.SocketTimeoutException;
import java.nio.charset.Charset;

/**
 * TODO
 *
 * @author zoey
 * @date 2021/1/29 16:29
 */
@Slf4j
public class HttpClientUtils {

    /**
     * 发送HttpClient请求
     * @param requestUrl
     * @param requestParams
     * @return
     */
    public static String sendPost(String requestUrl,String requestParams) {
        JSONObject jb = new JSONObject();
        jb.put("code",0);
        try {
            CloseableHttpClient httpClient = HttpClients.createDefault();
            RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(300 * 1000)
                .setConnectTimeout(300 * 1000)
                .build();
            HttpPost post = new HttpPost(requestUrl);
            post.setConfig(requestConfig);
            post.setHeader("Content-Type","application/json;charset=utf-8");
            StringEntity postingString = new StringEntity(requestParams,Charset.forName("UTF-8"));
            post.setEntity(postingString);
            HttpResponse response = httpClient.execute(post);
            String content = EntityUtils.toString(response.getEntity());
            log.info("接口返回内容为:" + content);
            return content;
        } catch (SocketTimeoutException e) {
            log.error("调用接口超时,超时时间:" + 300+ "秒,url:" + requestUrl + ",参数:" + requestParams, e);
            return jb.toString();
        } catch (Exception e) {
            log.error("调用接口失败,url:" + requestUrl + ",参数:" + requestParams,e);
            return jb.toString();
        }
    }
}

二、通过UrlConnection的方式

package com.zoey.http.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.IOUtils;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;

/**
 * 使用URLConnection连接,调用其他项目的接口
 *
 * @author zoey
 * @date 2021/1/29 17:06
 */
@Slf4j
public class URLConnectionUtils {


    public static String sendPost(String URL,String parameter) {
        System.out.println("发起的数据:" + parameter);
        byte[] requestParameter = parameter.getBytes();
        InputStream instr = null;
        java.io.ByteArrayOutputStream out = null;
        BufferedReader br = null;
        StringBuffer buffer = new StringBuffer();
        try {
            java.net.URL url = new URL(URL);
            URLConnection urlCon = url.openConnection();
            urlCon.setDoOutput(true);
            urlCon.setDoInput(true);
            urlCon.setUseCaches(false);
            urlCon.setRequestProperty("content-Type", "application/json");
            urlCon.setRequestProperty("charset", "utf-8");
            urlCon.setRequestProperty("Content-length",String.valueOf(requestParameter.length));
            DataOutputStream printout = new DataOutputStream(urlCon.getOutputStream());
            printout.write(requestParameter);
            printout.flush();
            printout.close();
            // 将返回的输入流转换成字符串
            br = new BufferedReader(new InputStreamReader(urlCon.getInputStream(), Charset.forName("UTF-8")));
            String temp;
            while ((temp = br.readLine()) != null) {
                buffer.append(temp);
            }
            System.out.println("接口返回内容为:" + buffer);
            return buffer.toString();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if(out!=null){
                    out.close();
                }
                if(instr!=null){
                    instr.close();
                }
            } catch (Exception ex) {
            }
        }
        return null;
    }

}

三、通过PostMethod的方式

package com.zoey.http.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;

import java.io.*;
import java.nio.charset.Charset;

/**
 * TODO
 *
 * @author zoey
 * @date 2021/1/29 17:13
 */
@Slf4j
public class PostMethodUtils {

    /**
     * 发送HttpClient请求
     * @param requestUrl
     * @param params
     * @return
     */
    public static String sendPost(String requestUrl, String params) {
        InputStream inputStream = null;
        try {
            HttpClient httpClient = new HttpClient();
            PostMethod postMethod = new PostMethod(requestUrl);
            // 设置请求头  Content-Type
            postMethod.setRequestHeader("Content-Type", "application/json");
            RequestEntity requestEntity = new StringRequestEntity(params,"application/json","UTF-8");
            postMethod.setRequestEntity(requestEntity);
            httpClient.executeMethod(postMethod);// 执行请求
            inputStream =  postMethod.getResponseBodyAsStream();// 获取返回的流
            BufferedReader br = null;
            StringBuffer buffer = new StringBuffer();
            // 将返回的输入流转换成字符串
            br = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("UTF-8")));
            String temp;
            while ((temp = br.readLine()) != null) {
                buffer.append(temp);
            }
            log.info("接口返回内容为:" + buffer);
            return buffer.toString();
        } catch (Exception e){
            log.info("请求异常" +e.getMessage());
            throw new RuntimeException(e.getMessage());
        } finally {
            if(inputStream != null) {
                try{
                    inputStream.close();
                } catch (IOException e){
                    e.printStackTrace();
                }
            }
        }
    }
}

四、引入依赖如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.2</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.zoey</groupId>
    <artifactId>http</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>http</name>
    <description>Http project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.3.5</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.70</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.6</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-io</artifactId>
            <version>1.3.2</version>
        </dependency>
        <dependency>
            <groupId>commons-httpclient</groupId>
            <artifactId>commons-httpclient</artifactId>
            <version>3.1</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

五、测试类如下:

package com.zoey.http.web.rest;

import com.zoey.http.utils.HttpClientUtils;
import com.zoey.http.utils.PostMethodUtils;
import com.zoey.http.utils.URLConnectionUtils;
import org.springframework.web.bind.annotation.RestController;

/**
 * 调用其他项目的接口
 * 1、使用HttpClient
 * 2、使用UrlConnection
 * 3、使用PostMethod
 * @author zoey
 * @date 2021/1/29 16:26
 */
@RestController
public class HttpPostTest {
    private static final String requestUrl = "http://xxx/api/wechat/report/search/all";


    /**
     * 使用HttpClient的方式连接
     */
    public static void queryByHttpClient(){
       String parameter = "{ \"dto\":{\"purchaserPhone\":\"13792472283\" }}";
       String response =  HttpClientUtils.sendPost(requestUrl,parameter);
    }

    /**
     * 使用UrlConnection的方式连接
     */
    public static void queryByUrlConnection() {
        String parameter = "{ \"dto\":{\"purchaserPhone\":\"13798479813\" }}";
        URLConnectionUtils.sendPost(requestUrl,parameter);
    }

    /**
     * 使用UrlConnection的方式连接
     */
    public static void queryByPostMethod(){
        String parameter = "{ \"dto\":{\"purchaserPhone\":\"13798479813\" }}";
        PostMethodUtils.sendPost(requestUrl,parameter);
    }


    public static void main(String[] args) {
        queryByHttpClient();
        queryByUrlConnection();
        queryByPostMethod();
    }
}

六、请求效果输入如下:

{
 "status":200,
 "data":[
  {
   "createdByEmployee":10612514,
   "createdByEmployeeName":"小明",
   "createdByDept":550201,
   "createdByDeptCode":"AKJSZX",
   "createdByDeptName":"安康技术中心",
   "createdDate":"2020-12-05"
  }
 ]
}

参考链接:https://www.cnblogs.com/feiyangbahu/p/9640261.html

  • 1
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值