java 创建请求对象_发送 HTTP 请求(Java)

操作步骤

API 网关提供了一个 JAVA SDK,即 gateway-sdk。该 SDK 集成了加签、验签的逻辑,同时默认支持序列化和反序列化。使用该 SDK 接入调用 HTTP 服务的操作步骤如下:

引入 SDK

您需要在本地工程 pom.xml 中添加如下 SDK。

com.alipay.sofa

gateway-sdk

2.0.3

构建 request 对象

您需要构建 request 对象,用于组装请求,代码示例如下:publicclassParamPostRequestimplementsApiRequest{

// 请求参数

Map params =newHashMap<>();

// 请求header

Map headers =newHashMap<>();

privateString apiVersion ="1.0";

// downstream 的 uri

privateString path;

// 网关强制开启验签加签

privateboolean clientCheckSign =true;

@Override

publicString getPath(){

return path;

}

publicvoid setPath(String path){

this.path = path;

}

@Override

publicString getApiMethodName(){

return"test";

}

@Override

publicMap getBizParams(){

return params;

}

@Override

publicString getApiVersion(){

return apiVersion;

}

@Override

publicvoid setApiVersion(String apiVersion){

this.apiVersion = apiVersion;

}

@Override

publicString getRequestType(){

return"POST";

}

@Override

publicClass getResponseClass(){

returnParamResponse.class;

}

@Override

publicMap getHeaderParams(){

return headers;

}

@Override

publicboolean checkSign(){

return clientCheckSign;

}

publicvoid setClientCheckSign(boolean clientCheckSign){

this.clientCheckSign = clientCheckSign;

}

}

构建 response 对象

您需要构建 response 对象,用于接收响应,代码示例如下:publicclassParamResponseextendsApiResponse{

privateString path;

publicString getPath(){

return path;

}

publicvoid setPath(String path){

this.path = path;

}

}

创建 apiClient

使用获取的 AK、SK、host 创建一个 apiClient,代码示例如下:privateString subAppAccessKey ="m9hoHiqtjylGjqXC";

privateString subAppSecretKey ="sxCg1uk6UjGARr1hPswE0W2KHe86YvhX";

privateString gatewayUrl ="https://5jzkcn0idt3w4czs.apigateway.inc.alipay.net";

//开启数据加密后,在调用请阅的 API 时必须传入应用的 AK 和 SK 完成加签。

privateApiClient apiClient;

@Before

publicvoid initClient(){

// 初始化请求客户端

ApiSecretKey apiSecretKey =newApiSecretKey(subAppAccessKey, subAppSecretKey);

List secretKeys =newArrayList<>();

secretKeys.add(apiSecretKey);

apiClient =newDefaultApiClient(gatewayUrl, secretKeys);

}

发起调用请求

apiClient 配置完成之后,即可对 API 发起调用。响应会自动序列化到 response 对象里,直接使用即可,代码示例如下:@Test

publicvoid testNoSignHttp(){

ParamPostRequest request =newParamPostRequest();

request.setPath("simple/demo");

// 是否对响应进行签名校验

request.setClientCheckSign(false);

ApiResponse response = apiClient.execute(request);

System.out.println(JSON.toJSONString(response));

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值