我是靠谱客的博主 落寞花生,这篇文章主要介绍.net接口使用java httpClient请求参数 使用RestTemplate,现在分享给大家,希望可以做个参考。

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

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

 

emmmm....

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

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

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

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

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

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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; }

调用:

复制代码
1
2
3
4
5
List<NameValuePair> pairs = new ArrayList<NameValuePair>(); NameValuePair pair = new BasicNameValuePair("userName","admin"); pairs.add(pair); NameValuePair pair = new BasicNameValuePair("password","123"); pairs.add(pair);
复制代码
1
HttpClient.sendHttpRequestPost("http://xxx.xxx.xx.xx:xxxx/xxxx",pairs,"application/x-www-form-urlencoded");

 

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

复制代码
1
2
3
4
5
6
7
8
9
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

最后

以上就是落寞花生最近收集整理的关于.net接口使用java httpClient请求参数 使用RestTemplate的全部内容,更多相关.net接口使用java内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(63)

评论列表共有 0 条评论

立即
投稿
返回
顶部