在代码Service层发起Http请求并获取结果

POST请求

HttpRequest

1)import cn.hutool.http.HttpRequest;中发送post请求使用.form

import cn.hutool.http.HttpRequest;

// 对 URL 执行 POST 请求,并获取请求结果String类型
String res = HttpRequest.post("https://api.weixin.qq.com/sns/jscode2session")
        .form("appid", appId)
        .form("secret", appSecret)
        .form("js_code", code)
        .form("grant_type", grantType)
        .execute().body();

// 解析相应内容(转换成json对象)
JSONObject json = JSONObject.parseObject(res);
log.info("解析code请求结果:"+json.toString());
String openid = json.getString("openid");
map.put("openid", openid);
String session_key= json.getString("session_key");
log.info("session_key:"+session_key);

2)import cn.hutool.http.HttpRequest;中发送post请求使用.body

如何获得.body中的内容:

  1. 有实体类:
        GoodsParam param= new GoodsParam();
        goodsParam.setOrder_id(outTradeNo);
        goodsParam.setEnv(env);
        String postBody = JSON.toJSONString(goodsParam);
  2. 无实体类1:
        // 构建 JSON 字符串
        // import com.alibaba.fastjson2.JSONObject;
        JSONObject requestBody = new JSONObject();
        requestBody.put("order_id", outTradeNo);
        requestBody.put("env", env);
        String postBody = requestBody.toJSONString();
  3. 无实体类2:
        String tokenUrl = String.format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s", wechatId, wechatSecret);
        JSONObject token = JSON.parseObject(HttpUtil.get(tokenUrl));
        accessToken = token.getString("access_token");
        
        String postUrl = String.format("https://api.weixin.qq.com/wxa/generatescheme?access_token=%s", accessToken);
        
        Map<String, Object> map = new HashMap<>();
        WechatSchemeParam wechatSchemeParam = new WechatSchemeParam();
        wechatSchemeParam.setPath("/pages/publishHomework/publishHomework");
        wechatSchemeParam.setQuery("");
        map.put("jump_wxa", wechatSchemeParam);
        map.put("expire_time", 1606737600);
        map.put("is_expire", true);
        
        String body = HttpRequest.post(postUrl).body(JSONObject.toJSONString(map)).execute().body();
        
        JSONObject resultJsonObject = JSON.parseObject(body);
        Integer errcode = resultJsonObject.getInteger("errcode");
        String errmsg = resultJsonObject.getString("errmsg");
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;

// 构造请求体
String clickId = "xxx";
// event_weight 为浮点数类型,所以不要""
String requestBody = "{ \"event_type\": \"" + investParam.getEventType() + "\", \"event_weight\": " + investParam.getFee().doubleValue() + ", \"context\": { \"ad\": { \"callback\": \"" + investParam.getClickId() + "\" } }, \"timestamp\": " + System.currentTimeMillis() + " }";

HttpResponse response = HttpRequest.post("https://analytics.oceanengine.com/api/v2/conversion")
        .header("Content-Type", "application/json")  // 设置请求头
        .body(requestBody).execute();

log.info("response:"+response);
String body = response.body();
log.info(body);



// 请求体如下:
{
    "event_type": "active", 
    "context": {
        "ad": {
            "callback": "EPHk9cX3pv4CGJax4ZENKI7w4MDev_4C",//callback 这里需要填写的就是从启动参数里获取的 clickid
        }
       
    },
    "timestamp": 1604888786102
}

// 得到的 HttpResponse response
Response Headers: 
    null=[HTTP/1.1 200 OK]
    Server=[Tengine]
    Server-Timing=[inner; dur=51, tt_agw; dur=47]
    Connection=[keep-alive]
    EagleId=[dd82c12c17001195895082728e]
    X-Tt-Logid=[202311161526299A2E1953EDDADEB2812F]
    Date=[Thu, 16 Nov 2023 07:26:29 GMT]
    Via=[cache33.l2et2[138,0], ens-vcache24.cn4621[141,0]]
    x-tt-trace-host=[01fc63e5394a782d9cb2112036abbbea261d453fcdea3d2ace0a66ba3c8923b9a74cf3e09a9d497a06d2628a90e33de7f20186243bda5cdf46a77eba728ce212c148a518a8d0168db0be1145f18a3f67a9299b440ff8d7d74989c7dc203e280c02]
    X-Tt-Agw-Login=[0]
    Timing-Allow-Origin=[*]
    server-timing=[cdn-cache;desc=MISS,edge;dur=3,origin;dur=138]
    x-tt-trace-tag=[id=03;cdn-cache=miss;type=dyn]
    Content-Length=[29]
    Content-Type=[application/json; charset=utf-8]
Response Body: 
    {"code":0,"message":"成功"}

// 得到的 body
{"code":0,"message":"成功"}

HttpPost+CloseableHttpClient

import org.apache.http.client.methods.HttpPost;和import org.apache.http.impl.client.CloseableHttpClient;

    String url = "https://ocpc.baidu.com/ocpcapi/api/uploadConvertData";
    List<ConversionType> conversionTypeList = new ArrayList<>();
    // 实体类对象
    ConversionType conversionType = new ConversionType();
    // 实例存入值
    conversionType.setConvert_type(investParam.getEventType());
    conversionType.setLogid_url(investParam.getLogid_url());
    // 存入集合
    conversionTypeList.add(conversionType);
    JsonObject data = new JsonObject();
    // 设置API接口回传Token
    // addProperty(String property, String value)
    data.addProperty("token", baiduToken);

    // 设置API接口回传conversionTypes
    // add(String property, JsonElement value)
    data.add("conversionTypes", new Gson().toJsonTree(conversionTypeList, new TypeToken<List<ConversionType>>() {}.getType()).getAsJsonArray());
    // 发送的完整请求数据
    System.out.println("req data: " + data.toString());

    // import org.apache.http.impl.client.CloseableHttpClient;
    CloseableHttpClient client = HttpClients.createDefault();
    
    // import org.apache.http.client.methods.HttpPost;
    HttpPost post = new HttpPost(url);
    post.setHeader("Content-type", "application/json; charset=UTF-8");
    // data 为 JSONObject(key-value 结构)类型
    StringEntity entity = new StringEntity(data.toString(), Charset.forName("UTF-8"));
    entity.setContentEncoding("UTF-8");
    post.setEntity(entity);

    org.apache.http.HttpResponse response =  client.execute(post);
    // 检验状态码,如果成功接收数据
    int code = response.getStatusLine().getStatusCode();

GET请求

HttpRequest

import cn.hutool.http.HttpRequest;

// 对 URL(investUrl) 发起 GET 请求得到String类型的结果
String body = HttpRequest.get(investUrl).execute().body();
log.info("body:"+body);

// 结果举例
body:{ "status" : 811, "message" : "impression id expired." }

HttpUtil

String tokenUrl = String.format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s", appId, appSecret);

HttpUtil.get(tokenUrl);

使用Spring的 RestTemplate

Spring 的 `RestTemplate` 提供了多个方法,用于支持不同的 HTTP 请求方法和处理响应。以下是一些常见的方法:

前提代码(请求体等):

//通过token和code来获取用户手机号
String url = "https://api.weixin.qq.com/wxa/sec/vod/listmedia?access_token=" + getAccessToken();
//封装请求体
Map<String, String> paramMap = Maps.newHashMap();
paramMap.put("drama_id", dramaId);
//封装请求头
HttpHeaders headers = getHeaders();
HttpEntity<Map<String, String>> httpEntity = new HttpEntity<>(paramMap,headers);

1. GET 请求:

ResponseEntity<Object> response = restTemplate.getForEntity(url, Object.class);

使用 `getForEntity` 方法发送 GET 请求,获取响应的 `ResponseEntity`,并指定响应体的类型为 `Object.class`。

2. POST 请求:

ResponseEntity<Object> response = restTemplate.postForEntity(url, httpEntity, Object.class);

使用 `postForEntity` 方法发送 POST 请求,将请求体 `httpEntity` 发送到指定的 `url`,并获取响应的 `ResponseEntity`。

3. PUT 请求:

restTemplate.put(url, httpEntity);

使用 `put` 方法发送 PUT 请求,将请求体 `httpEntity` 发送到指定的 `url`。

4. DELETE 请求:

restTemplate.delete(url);

使用 `delete` 方法发送 DELETE 请求,删除指定的资源。

5. Exchange 方法:

ResponseEntity<Object> response = restTemplate.exchange(url, HttpMethod.GET, httpEntity, Object.class);

使用 `exchange` 方法可以发送任意类型的 HTTP 请求,包括 GET、POST、PUT、DELETE 等。它提供了更灵活的选项,可以指定请求方法、请求头等。

6. Head 请求:

HttpHeaders headers = restTemplate.headForHeaders(url);

 使用 `headForHeaders` 方法发送 HEAD 请求,获取响应的头信息。

7. Options 请求:

Set<HttpMethod> options = restTemplate.optionsForAllow(url);

使用 `optionsForAllow` 方法发送 OPTIONS 请求,获取支持的 HTTP 方法。

注意:以上Spring 的 RestTemplate 中的HTTP请求方法的响应结果不会存入redis中。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值