HttpClient请求无参数问题

通过HttpClien 调用API的时候服务端返回缺少参数

以下是原来的第三的服务商提供的方法,使用后一直提示缺少返回值,

private static String sendHttpRequest(String url, Map<String, String> bodyMap)
 throws Exception {
    System.out.println("请求地址:" + url);
    System.out.println("发送参数:" + bodyMap.toString());
    HttpClient client = HttpClientBuilder.create().build();
    HttpPost postRequest = new HttpPost(url);
    postRequest.addHeader("Content-Type", "application/json;charset=UTF-8");
    postRequest.setHeader("Accept", "aplication/json");
    List<NameValuePair> nvps = new ArrayList<>();
    for (String key : bodyMap.keySet()) {
        nvps.add(new BasicNameValuePair(key, bodyMap.get(key)));
    }
    log.info("post请求:{}", nvps);
    postRequest.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
    int retry = 3;
    HttpResponse execute = null;
    while (retry-- > 0) {
        try {
            execute = client.execute(postRequest);
            break;
        } catch (Exception e) {
            Thread.sleep(5000);
        }
    }
    if (execute == null) {
        throw new Exception("接口请求失败");
    }
    String resp = EntityUtils.toString(execute.getEntity());
    System.out.println("接口返回:" + resp);
    return resp;
}

最后差了很多资料才知道使用HttpClient发送post请求时会遇到服务端收不到参数的情况,查找了一下原因是因为大部分使用Httpclient模拟post请求时都会把参数放在Entity里面,示例如下:

// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
// 创建参数列表
if (param != null) {
    List<NameValuePair> paramList = new ArrayList<>();
    for (String key : param.keySet()) {
        paramList.add(new BasicNameValuePair(key, param.get(key)));
    }
    // 模拟表单
    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
    httpPost.setEntity(entity);
}
// 执行http请求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(),"utf-8");

上面的这种设置参数的方式通过request.getParameter(“key”)的方式获取不到参数,所以如果想通过request.getParameter(“key”)获取参数,则需要修改HttpClient模拟post请求时设置参数的方式,示例如下:

private static HttpPost postForm(String url, Map<String, String> params) {
		URIBuilder builder;
		HttpPost httpost = null;
		try {
			builder = new URIBuilder(url);
			
			List<NameValuePair> nvps = new ArrayList <NameValuePair>();
			Set<String> keySet = params.keySet();
			for(String key : keySet) {
				nvps.add(new BasicNameValuePair(key, params.get(key)));
			}
			
			builder.setCharset(Consts.UTF_8);
			builder.setParameters(nvps);
			httpost = new HttpPost(builder.build());
		} catch (URISyntaxException e) {
			e.printStackTrace();
		}
		return httpost;	
	}

API返回的数据中带有斜杠

终于解决了上面的问题.结果发现返回的数据是这样的…

{“online”:true,“connect_time”:“2023-04-18
:54:35”,“status”:“SUCCESS”,“cid”:“20221005912”}

还是在返回的时候使用fastjson中的 JSON.parse() 方法即可处理完.

解决服务器无法接受参数的原文地址

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值