使用HTTP协议实现远程调用接口

1、引入maven依赖

  <dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.5</version>
  </dependency>

2、封装http工具类

package cn.toroot.bj.utils;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Map;

/**
 * @author Mr peng
 * Created on 2020-6-10 14:25:18.
 */
public class HttpUtil {

    private final static Logger logger = LoggerFactory.getLogger(HttpUtil.class);
    private static CloseableHttpClient httpClient;
    private static Charset UTF_8 = Charset.forName("UTF-8");
    private static RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(20000).setConnectTimeout(20000).build();

    static {
        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
        cm.setMaxTotal(200);
        cm.setDefaultMaxPerRoute(20);
        HttpHost localhost = new HttpHost("localhost", 80);
        cm.setMaxPerRoute(new HttpRoute(localhost), 50);

        httpClient = HttpClients.custom().setConnectionManager(cm).build();
    }

    public static String post(String url, String content) {
        logger.debug("{} - {}", url, content);
        HttpPost httppost = new HttpPost(url);
        httppost.setConfig(requestConfig);
        if (content != null) {
            HttpEntity httpEntity = new StringEntity(content, UTF_8);
            httppost.setEntity(httpEntity);
        }
        return execute(httppost);
    }

    public static String postFile(String url, String localFile, Map<String,String> stringParts) {
        logger.debug("{} - {}", url, localFile);
        HttpPost httppost = new HttpPost(url);
        httppost.setConfig(requestConfig);

        MultipartEntityBuilder build = MultipartEntityBuilder.create();
        build.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); //以浏览器兼容模式运行,防止文件名乱码
        build.setCharset(Charset.forName("utf-8"));

        if(null != localFile && localFile.length() > 0){
            FileBody fileBody = new FileBody(new File(localFile));
            build.addPart("file",fileBody);
        }

        if(null != stringParts) {
            for (Map.Entry<String, String> entry : stringParts.entrySet()) {
                StringBody stringBody = new StringBody(entry.getValue(), ContentType.create("text/plain", UTF_8));
                build.addPart(entry.getKey(), stringBody);
            }
        }

        HttpEntity reqEntity = build.build();

        httppost.setEntity(reqEntity);
        return execute(httppost);
    }

    public static String postFile(String url, String localFile) {
        return postFile(url,localFile,null);
    }

    public static String post4GzipResponse(String url, String content) {
        logger.debug("{} - {}", url, content);
        HttpPost httppost = new HttpPost(url);
        httppost.setConfig(requestConfig);
        httppost.addHeader("Accept-Encoding", "gzip");
        if (content != null) {
            HttpEntity httpEntity = new StringEntity(content, UTF_8);
            httppost.setEntity(httpEntity);
        }
        return execute(httppost);
    }

    /**
     * 以JSON的格式发送请求
     *
     * @param url
     * @param content
     * @return
     */
    public static String postAsJson(String url, String content) {
        logger.debug("{} - {}", url, content);
        HttpPost httppost = new HttpPost(url);
        httppost.setConfig(requestConfig);
        HttpEntity httpEntity = new StringEntity(content, ContentType.APPLICATION_JSON);
        httppost.setEntity(httpEntity);
        return execute(httppost);
    }

    public static String get(String url) {
        HttpGet httpGet = new HttpGet(url);
        httpGet.setConfig(requestConfig);
        return execute(httpGet);
    }

    private static String execute(HttpRequestBase httpRequestBase) {
        String result = null;
        try {
            HttpResponse response = httpClient.execute(httpRequestBase);
            HttpEntity resEntity = response.getEntity();
            if (resEntity != null) {
                result = EntityUtils.toString(resEntity, UTF_8);
                EntityUtils.consume(resEntity);
                if (result.length() < 2000) {
                    logger.debug(result);
                } else {
                    if (logger.isTraceEnabled()) {
                        logger.trace(result);
                    }
                }
            }
        } catch (IOException e) {
            logger.error("", e);
        }
        return result;
    }


    public static void main(String[] args) {
        String res = HttpUtil.get("http://www.baidu.com");
        System.out.println("res = " + res);
    }

    /**
     * 将对象转换成json,用post方法发送给服务器
     * @param url
     * @param intface
     * @param param
     * @return
     */
    public static String sendPost(String url, String intface, Object param) {
        return postAsJson(url + intface,JsonUtils.obj2json(param));
    }
}


  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java远程调用SOAP协议接口可以通过以下步骤实现: 1.首先,根据需要创建Java项目,可以使用Eclipse或其他Java开发工具。 2.在项目中导入相关的SOAP协议库,例如Apache Axis2或Apache CXF等。 3.根据接口的WSDL(Web Service Description Language)文件生成客户端代码。可以使用Axis2提供的WSDL2Java工具或CXF提供的wsdl2java命令来实现。这将根据WSDL文件生成相应的Java类和接口。 4.使用生成的客户端类和接口编写客户端代码。首先,创建一个调用服务的Java类。在该类中,实例化接口类并设置访问所需的URL、服务名称和命名空间等。然后,可以调用接口中的方法来实现具体的远程调用。 5.在方法中,根据接口方法的参数,创建所需的SOAP消息。可以使用SOAPEnvelope、SOAPBody、SOAPHeader等类来构造和设置消息的内容。根据需要添加SOAP Header或SOAP Body中的元素,并设置相应的值。 6.通过生成的客户端类调用接口的方法,并将消息作为参数传递给方法。该方法将负责将请求发送到服务端,并等待响应。 7.接收服务端返回的响应消息。可以通过客户端类中提供的方法来获取响应的内容,如SOAP Body中的元素值。 8.根据需要对响应进行解析,提取所需的数据。可以使用XPath或其他解析技术来处理返回的SOAP消息。 9.最后,根据业务逻辑处理响应数据,并根据需要执行后续操作。 综上所述,使用Java远程调用SOAP协议接口可以通过生成客户端代码、构造SOAP消息、调用接口方法并处理返回结果实现。这样可以实现与服务端之间的远程通信和数据传输。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值