Java调用RestFul接口

时间:2022-03-06 06:19:44

使用Java调用RestFul接口,以POST请求为例,以下提供几种方法:

一、通过HttpURLConnection调用

 1 public String postRequest(String url, String param) {
2 StringBuffer result = new StringBuffer();
3
4 HttpURLConnection conn = null;
5 OutputStream out = null;
6 BufferedReader reader = null;
7 try {
8 URL restUrl = new URL(url);
9 conn = (HttpURLConnection) restUrl.openConnection();
10 conn.setRequestMethod("POST");
11 conn.setDoOutput(true);
12 conn.setDoInput(true);
13
14 conn.setRequestProperty("accept", "*/*");
15 conn.setRequestProperty("connection", "Keep-Alive");
16 conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
17 conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
18
19 conn.connect();
20 out = conn.getOutputStream();
21 out.write(param.getBytes());
22 out.flush();
23
24 int responseCode = conn.getResponseCode();
25 if(responseCode != 200){
26 throw new RuntimeException("Error responseCode:" + responseCode);
27 }
28
29 String output = null;
30 reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
31 while((output=reader.readLine()) != null){
32 result.append(output);
33 }
34 } catch (Exception e) {
35 e.printStackTrace();
36 throw new RuntimeException("调用接口出错:param+"+param);
37 } finally {
38 try {
39 if(reader != null){
40 reader.close();
41 }
42 if(out != null){
43 out.close();
44 }
45 if(conn != null){
46 conn.disconnect();
47 }
48 } catch (Exception e2) {
49 e2.printStackTrace();
50 }
51 }
52
53 return result.toString();
54 }

二、通过Spring提供的RestTemplate模板调用

 1 public class RestTemplateUtil {
2
3 @Autowired
4 private RestTemplate restTemplate;
5
6 @Bean
7 public RestTemplate restTemplate(){
8 RestTemplate template = new RestTemplate();
9 // messageConverters是RestTemplate的一个final修饰的List类型的成员变量
10 // messageConverters的第二个元素存储的是StringHttpMessageConverter类型的消息转换器
11 // StringHttpMessageConverter的默认字符集是ISO-8859-1,在此处设置utf-8字符集避免产生乱码
12 template.getMessageConverters().set(1, new StringHttpMessageConverter(Charset.forName("utf-8")));
13 return template;
14 }
15
16 public String post(String url, String jsonParam){
17 // 自定义请求头
18 HttpHeaders headers = new HttpHeaders();
19 headers.setContentType(MediaType.APPLICATION_JSON);
20 headers.setAcceptCharset(Collections.singletonList(Charset.forName("utf-8")));
21 headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
22
23 // 参数
24 HttpEntity<String> entity = new HttpEntity<String>(jsonParam, headers);
25 // POST方式请求
26 ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
27 if(responseEntity == null){
28 return null;
29 }
30
31 return responseEntity.getBody().toString();
32 }
33
34 }

三、通过HttpClient调用

 1 public class HttpClientUtil {
2
3 public String post(String url, Map<String, Object> pramMap) throws Exception {
4 String result = null;
5 // DefaultHttpClient已过时,使用CloseableHttpClient替代
6 CloseableHttpClient closeableHttpClient = null;
7 CloseableHttpResponse response = null;
8 try {
9 closeableHttpClient = HttpClients.createDefault();
10 HttpPost postRequest = new HttpPost(url);
11 List<NameValuePair> pairs = new ArrayList<>();
12 if(pramMap!=null && pramMap.size() > 0){
13 for (Map.Entry<String, Object> entry : pramMap.entrySet()) {
14 pairs.add(new BasicNameValuePair(entry.getKey(), String.valueOf(entry.getValue())));
15 }
16 }
17 UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(pairs, "utf-8");
18 postRequest.setEntity(formEntity);
19
20 response = closeableHttpClient.execute(postRequest);
21 if(response!=null && response.getStatusLine().getStatusCode()==HttpStatus.SC_OK){
22 result = EntityUtils.toString(response.getEntity(), "utf-8");
23 }else{
24 throw new Exception("post请求失败,url" + url);
25 }
26
27 } catch (Exception e) {
28 e.printStackTrace();
29 throw e;
30 } finally {
31 try {
32 if(response != null){
33 response.close();
34 }
35 if(closeableHttpClient != null){
36 closeableHttpClient.close();
37 }
38 } catch (IOException e) {
39 e.printStackTrace();
40 }
41 }
42
43 return result;
44 }
45
46 }