HttpClient4.5和RestTemplate使用

普通form表单提交(application/x-www-form-urlencoded)

HttpPost post=new HttpPost(basePath)
HttpParams params=new BasicHttpParams()
params.setParameter("name",张三)
params.setParameter("age",18)
post.setParams(params)
CloseableHttpResponse response = httpClient.execute(post);


LinkedMultiValueMap map=new LinkedMultiValueMap()
map.add('name','张三')
map.add('age',18)
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED_VALUE)
HttpEntity req = new HttpEntity(map,headers);
ResponseEntity res=restTemplate.postForEntity(basePath,req,String.class)



JSON提交(application/json)

HttpPost post=new HttpPost(basePath)
post.setHeader("content-type","application/json;utf-8")
StringEntity=new StringEntity("{\"name\":\"张三\",\"age\":18}")
CloseableHttpResponse response = httpClient.execute(post);

HttpHeaders headers = new HttpHeaders();
       headers.setContentType(MediaType.APPLICATION_JSON)
         HttpEntity req = new HttpEntity("{\"name\":\"张三\",\"age\":18}",headers);
         ResponseEntity res=restTemplate.postForEntity(basePath,req,String.class)



你可能感兴趣的:(JAVA)