.net接口使用java httpClient请求参数 使用RestTemplate

1 篇文章 0 订阅
1 篇文章 0 订阅

HttpClient向接口发送请求,无返回值,发现接口未接收到所传参数的值,因为不是Java写的接口导致。

Springboot — 用更优雅的方式发HTTP请求(RestTemplate详解)

 

emmmm....

不解释太多了,直接转载别人用的方法吧,看不懂的可以直接复制我用的方法和调用。

https://blog.csdn.net/qicui2835/article/details/80945749

常规的get请求可以直接拼在url中的,这样可以直接传参数并成功接收。

但在post请求是必须要用BasicNameValuePair。

以下是我写的HttpClient类方法及调用:

public static String sendHttpRequestPost(String url,List<NameValuePair> pairs, String contentType)throws Exception {
        CloseableHttpClient client = HttpClients.createDefault();
        String respContent = null;
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Content-Type", contentType);

        StringEntity entity = new StringEntity(parameter,ContentType.APPLICATION_FORM_URLENCODED);
        entity.setContentEncoding("UTF-8");
        entity.setContentType("application/x-www.form-urlencoded");
        httpPost.setEntity(entity);
        httpPost.setEntity(new UrlEncodedFormEntity(pairs, HTTP.UTF_8));
        try {
            CloseableHttpResponse response = client.execute(httpPost);
            if (response.getStatusLine().getStatusCode() == 200) {
                HttpEntity he = response.getEntity();
                respContent = EntityUtils.toString(he, "UTF-8");
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return respContent;
    }

调用:

List<NameValuePair> pairs = new ArrayList<NameValuePair>();
NameValuePair pair = new BasicNameValuePair("userName","admin");
pairs.add(pair);
NameValuePair pair = new BasicNameValuePair("password","123"); 
pairs.add(pair);
HttpClient.sendHttpRequestPost("http://xxx.xxx.xx.xx:xxxx/xxxx",pairs,"application/x-www-form-urlencoded");

 

最新发现的另外一种方法特意加上去的哦 Springboot — 用更优雅的方式发HTTP请求(RestTemplate详解)

RestTemplate restTemplate = new RestTemplate();
String url = "http://xxx.xxx.xx.xx:xxxx/xxxx";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
MultiValueMap<String, String> map= new LinkedMultiValueMap<>();
map.add("deviceId", "all");
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);
ResponseEntity<String> response = restTemplate.postForEntity( url, request , String.class );
System.out.println(response.getBody());

测试过无问题,详细内容请看https://www.cnblogs.com/javazhiyin/p/9851775.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值