http参数自动转换java接口参数设置_使用httpClient调用接口,参数用map封装或者使用JSON参数,并转换返回结果...

这里接口用表存起来,标记请求方式,然后接受参数,消息或者请求参数都可以,

然后先是遍历需要调用的接口,封装参数,再分别调用get与post即可,没有微服务还是得自己写

//消息转发-获取参数中对应参数调用对应接口

public void pmsForward(Map map){

List address = forwardAddressHelper.getAddress();//从内存获取转发地址

//封装参数

List params = new ArrayList();

Iterator> iterator = map.entrySet().iterator();

while(iterator.hasNext()){

Map.Entry next = iterator.next();

params.add(new BasicNameValuePair(next.getKey(),next.getValue()));

}

address.forEach(x->{

if(StringUtil.isNotEmpty(x.getType())){

if(StringUtil.equals(x.getType(),"GET")){

//get请求

pmsForwardService.getInvoking(x.getAddress(),params);

}else if(StringUtil.equals(x.getType(),"POST")){

//post请求

pmsForwardService.postInvoking(x.getAddress(),params);

}

}else{

log.debug("所请求地址请求方式为空:"+x.getId()+","+x.getAddress());

}

});

}

,然后是get调用与post调用:

public void getInvoking(String address, List params) {

log.debug("进入get接口调用,参数:"+params+",地址:"+address);

CloseableHttpResponse response = null;

CloseableHttpClient httpClient = HttpClients.createDefault();

try {

URIBuilder builder = new URIBuilder(address);

builder.setParameters(params);

HttpGet get = new HttpGet(builder.build());

response = httpClient.execute(get);

if(response != null && response.getStatusLine().getStatusCode() == 200){

HttpEntity entity = response.getEntity();

log.info("pms消息转发成功,返回结果"+entityToString(entity));

}

} catch (Exception e) {

e.printStackTrace();log.error("pms消息转发失败"+response.getEntity());

} finally {

try {

httpClient.close();if(response != null)response.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}

@Override

public void postInvoking(String address, List params) {

log.debug("进入post接口调用,参数:"+params+",地址:"+address);

CloseableHttpClient httpClient = HttpClients.createDefault();

HttpPost post = new HttpPost(address);

CloseableHttpResponse response = null;

try {

post.setEntity(new UrlEncodedFormEntity(params,"UTF-8"));

response = httpClient.execute(post);

if(response != null && response.getStatusLine().getStatusCode() == 200){

HttpEntity entity = response.getEntity();

log.info("pms消息转发成功,返回结果"+entityToString(entity));

}

} catch (Exception e) {

e.printStackTrace();log.error("pms消息转发失败"+response.getEntity());

} finally {

try {

httpClient.close();

if(response != null) {

response.close();

}

} catch (IOException e) {

e.printStackTrace();

}

}

}

,最后是将response转换成String的方法:

//解析httpclient返回结果,转换成String

private String entityToString(HttpEntity entity) throws IOException {

String result = null;

if(entity != null)

{

long lenth = entity.getContentLength();

if(lenth != -1 && lenth < 2048){

result = EntityUtils.toString(entity,"UTF-8");

}else {

InputStreamReader reader1 = new InputStreamReader(entity.getContent(), "UTF-8");

CharArrayBuffer buffer = new CharArrayBuffer(2048);

char[] tmp = new char[1024];

int l;

while((l = reader1.read(tmp)) != -1) {

buffer.append(tmp, 0, l);

}

result = buffer.toString();

}

}

return result;

}

可以debug查看结果了!

还有就是直接使用JSON封装参数:

POST: 只需要设置一下请求头就行了

CloseableHttpClient httpClient = HttpClients.createDefault();

HttpPost post = new HttpPost(address);

post.setHeader("Content-Type", "application/json;charset=UTF-8");

String parameter = GSON.toJson(params);

StringEntity se = new StringEntity(parameter);

se.setContentType(CONTENT_TYPE_TEXT_JSON);

post.setEntity(se);

CloseableHttpResponse response = null;

try {

response = httpClient.execute(post);

if(response != null && response.getStatusLine().getStatusCode() == 200){

HttpEntity entity = response.getEntity();

log.info("消息转发成功,返回结果"+entityToString(entity));

}

} catch (Exception e) {

e.printStackTrace();log.error("消息转发失败"+response.getEntity());

} finally {

try {

httpClient.close();

if(response != null) {

response.close();

}

} catch (IOException e) {

e.printStackTrace();

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,关于JAVA调用接口传递参数和接收JSON数据,可以通过以下步骤来实现: 1.导入相关的依赖包,例如Apache HttpClient、FastJSON等。 2.构造请求参数转换JSON格式。可以使用FastJSONJava对象转换JSON字符串。 3.创建HttpClient对象,并设置请求方法、请求头、请求体等参数。请求方法为POST,请求头中需要设置Content-Type为application/json。 4.执行请求并获取响应。可以使用HttpClient执行请求,并获取响应。响应中包含了接口返回JSON数据。 5.解析JSON数据并处理结果。可以使用FastJSONJSON字符串转换Java对象,然后根据接口返回的数据进行相应的处理。 以下是示例代码: ```java import java.io.IOException; import java.util.HashMap; import java.util.Map; import org.apache.http.HttpEntity; import org.apache.http.HttpHeaders; import org.apache.http.client.methods.CloseableHttpResponse; 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.HttpClients; import org.apache.http.util.EntityUtils; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; public class InterfaceTest { public static void main(String[] args) throws IOException { // 构造请求参数 Map<String, Object> params = new HashMap<String, Object>(); params.put("username", "test"); params.put("password", "123456"); String jsonStr = JSON.toJSONString(params); // 创建HttpClient对象 CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost("http://localhost:8080/api/login"); // 设置请求头 httpPost.setHeader(HttpHeaders.CONTENT_TYPE, "application/json"); // 设置请求体 StringEntity stringEntity = new StringEntity(jsonStr, "UTF-8"); httpPost.setEntity(stringEntity); // 执行请求并获取响应 CloseableHttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); String responseStr = EntityUtils.toString(httpEntity, "UTF-8"); // 解析JSON数据并处理结果 JSONObject jsonObject = JSON.parseObject(responseStr); int code = jsonObject.getIntValue("code"); String message = jsonObject.getString("message"); if (code == 0) { // 登录成功 String token = jsonObject.getString("token"); System.out.println("登录成功,Token为:" + token); } else { // 登录失败 System.out.println("登录失败,原因:" + message); } // 关闭HttpClient和响应流 httpResponse.close(); httpClient.close(); } } ``` 注意:以上代码仅供参考,具体实现需要根据接口的具体要求进行调整。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值