【Web后端】java发起HTTP请求

引入依赖

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

导入jar包

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
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.HttpClientBuilder;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

发起HTTP请求

get方法

String url = "url";
//创建HttpClient对象
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpGet httpGet = new HttpGet(url);
try {
    HttpResponse response = httpClient.execute(httpGet);
    //HttpStatus.SC_OK = 200
    if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        JSONObject obj = JSONObject.parseObject(res);
        System.out.println(obj);
    }
} catch (IOException e) {
    e.printStackTrace();
}

post方法

JSONObjcet result = new JSONObject();

// 创建HttpPost对象,设置URL地址
HttpPost httpPost=new HttpPost(URL);

// 封装参数
JSONObject param = new JSONObject();
param.put("name","tom");

//装填参数
StringEntity entity = new StringEntity(param.toString(), "utf-8");
entity .setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json"));

//设置参数到请求对象中
httpPost.setEntity(entity);

//设置报头
httpPost.setHeader("Content-type", "application/json");

try{
    //执行请求操作,并拿到结果(同步阻塞)
    CloseableHttpResponse response = httpClient.execute(httpPost);
    //获取结果实体
    HttpEntity entity = response.getEntity();
    if (entity != null) {
        //按指定编码转换结果实体为String类型
        String res = EntityUtils.toString(entity, "UTF-8");
        result= JSONObject.parseObject(res);
    }
    //释放链接
    response.close();
}catch (IOException e) {
    e.printStackTrace();
}

return result;

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Cimoon_

一分也是爱,用钱砸我

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值