HTTP远程调用(post)

论坛 期权论坛 脚本     
匿名技术用户   2021-1-3 23:37   11   0

1.开发中遇到服务间通过restful接口进行调用的情况,可以使用如下的方式进行实现:

maven依赖如下:

        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.2</version>
        </dependency>
package com.shencai.xf.common.util;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;


/**
 * @Description: 描述
 * @Author: xuyahui
 * @Date: 2019/8/13 17:17
 * @Version 1.0
 */
public class HttpUtil {

    private static Logger logger = LoggerFactory.getLogger(HttpUtil.class.getName());

    private static HttpClient httpClient = HttpClientBuilder.create().build();
    private final static String CHARSET = "UTF-8";

    public static String post(String url, String json) {
        HttpPost post = new HttpPost(url);
        post.addHeader(HTTP.CONTENT_TYPE, "application/json");
        StringEntity entity = new StringEntity(json, CHARSET);
        post.setEntity(entity);
        try {
            HttpResponse response = httpClient.execute(post);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                if (response.getEntity() != null) {
                    return EntityUtils.toString(response.getEntity(), CHARSET);
                }
            }
            throw new IOException("请求出错");
        } catch (IOException e) {
            e.printStackTrace();
            logger.error(e.getMessage());
        }
        return null;
    }

}

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:7942463
帖子:1588486
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP