HttpClient解决postman中传输x-www-form-urlencoded数据

public  static  String doPostJson(String url,String key,String json){
    try {
        String postURL=url;
        PostMethod postMethod = null;
        postMethod = new PostMethod(postURL) ;
        postMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8") ;
        postMethod.addParameter(key,json);  //传参数
        HttpClient httpClient = new HttpClient();
        int response = httpClient.executeMethod(postMethod); // 执行POST方法
        String result = postMethod.getResponseBodyAsString() ;
        return result;
    } catch (Exception e) {
 
        throw new RuntimeException(e.getMessage());
    }
}


 

Postman,当你选择"X-www-Form-urlencoded"作为发送请求体的内容类型时,其键值对是以查询参数的形式呈现的,例如:`key1=value1&key2=value2`。对应的Java HTTP客户端(如Apache HttpClient、Spring RestTemplate等)处理这种格式的请求体通常需要设置`application/x-www-form-urlencoded` Content-Type,并通过`MultiValueMap`或者`HttpEntity`来传递。 以下是使用`org.apache.http.client.entity.StringEntity`的例子: ```java import org.apache.http.HttpEntity; 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.message.BasicNameValuePair; CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost("http://your-api-url.com"); // 创建一个NameValuePair数组,包含键值对 BasicNameValuePair[] params = new BasicNameValuePair[] { new BasicNameValuePair("key1", "value1"), new BasicNameValuePair("key2", "value2") }; try { // 设置请求体为X-www-Form-urlencoded格式 httpPost.setEntity(new StringEntity(urlEncode(params), ContentType.APPLICATION_FORM_URLENCODED)); CloseableHttpResponse response = httpClient.execute(httpPost); // ...处理响应... } finally { httpClient.close(); } // 将参数转换为URL编码的字符串 private String urlEncode(BasicNameValuePair... params) { StringBuilder encodedParams = new StringBuilder(); for (BasicNameValuePair param : params) { encodedParams.append(param.getName()).append("=").append(URLEncoder.encode(param.getValue(), "UTF-8")).append("&"); } return encodedParams.toString().substring(0, encodedParams.length() - 1); // 去掉最后一个 & } ``` 这里假设你已经有了一个API URL。注意在实际应用,记得处理可能出现的异常,比如网络连接错误、编码错误等。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值