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

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

ps:主要解决在webservice中,我们想从另外一个项目调用webservice项目接口,也就是跨项目调用接口 这里主要用到了xfire wsdl 废话不说了 直接上东西 1. 首先新建一个项目 2. 在src下创建两个文件: a) 第一个是你想要访问的webservice的接口,比如我想访问的接口是 ReleaseService 那就在当前项目创建一个ReleaseService接口(接口中的方法必须和你想要访问的webservice的接口中的方法相同) b) 第二个是你的调用类 3. 导入相应的jar包,这些包不能引用,一定要复制到lib文件夹下面在引用 4. 具体的实现代码 TestWebService方法的代码: package com.isanta.webServiceTest; import java.io.InputStream; import java.net.MalformedURLException; import java.util.Properties; import java.util.Scanner; import org.codehaus.xfire.XFireFactory; import org.codehaus.xfire.client.XFireProxyFactory; import org.codehaus.xfire.service.Service; import org.codehaus.xfire.service.binding.ObjectServiceFactory; public class TestWebService { /** * @param args */ public static void testWebService() throws MalformedURLException, Exception{ // TODO Auto-generated method stub /** *这里是我的参数放在了properties文件中,我在读取里面的参数,这里我们也可以通过方法传参数 *如 : testWebService(String url,String xMlStr)() 那么在调用的时候就可以直接传进来了 *url 是你访问的webservice 的tomcat 的服务器地址 */ Properties pro = new Properties(); InputStream in = null; in = TestWebService.class.getResourceAsStream("/request.properties"); pro.load(in); String url = pro.getProperty("url"); String xMLstr = pro.getProperty("xMLstr"); Service s=new ObjectServiceFactory().create(ReleaseService.class); XFireProxyFactory xf=new XFireProxyFactory(XFireFactory.newInstance().getXFire()); System.out.println("url="+url); try { //这里就是获取webservice的接口的实例对象 ReleaseService seleaseService=(ReleaseService) xf.create(s,url); System.out.println("进入接口----------------->请求报文:"+xMLstr); //这里就是调用你需要的接口的方法 String st=seleaseService.queryReceiptDatas(xMLstr); System.out.print(st); } catch(Exception e) { e.printStackTrace(); } } } 5. 将整个项目打包成jar 6. 将打好的jar包引入到你想要调用项目中,然后就想 正常的代码一样来调用,如: import java.net.MalformedURLException; import com.isanta.webServiceTest.TestWebService; public class Test { public static void main(String[] args) throws MalformedURLException, Exception { TestWebService.testWebService(); } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值