HTTP远程调用(Post & Get)

开发中遇到服务间通过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();

    public static String httpPost(String url, String json) {
        HttpPost post = new HttpPost(url);
        post.addHeader(HTTP.CONTENT_TYPE, "application/json");
        StringEntity entity = new StringEntity(json, "UTF-8");
        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(), "UTF-8");
                }
            }
            throw new IOException("请求出错");
        } catch (IOException e) {
            e.printStackTrace();
            logger.error(e.getMessage());
        }
        return null;
    }

    public static JSONObject httpGet(String url){
        JSONObject jsonObject = null;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet get = new HttpGet(url);
        try {
            HttpResponse response = httpClient.execute(get);
            HttpEntity entity = response.getEntity();
            String returnString= EntityUtils.toString(entity, "UTF-8");
            EntityUtils.consume(entity);
            jsonObject = JSONObject.parseObject(returnString);
        } catch (IOException e) {
            LOG.error("http请求失败", e);
        }
        return jsonObject;
    }

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值