使用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模板调用
public class RestTemplateUtil { @Bean public RestTemplate restTemplate(){ RestTemplate template = new RestTemplate(); // messageConverters是RestTemplate的一个final修饰的List类型的成员变量 // messageConverters的第二个元素存储的是StringHttpMessageConverter类型的消息转换器 // StringHttpMessageConverter的默认字符集是ISO-8859-1,在此处设置utf-8字符集避免产生乱码 template.getMessageConverters().set(1, new StringHttpMessageConverter(Charset.forName("utf-8"))); return template; } @Autowired private RestTemplate restTemplate; public String post(String url, String jsonParam){ // 自定义请求头 HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); headers.setAcceptCharset(Collections.singletonList(Charset.forName("utf-8"))); headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); // 参数 HttpEntity<String> entity = new HttpEntity<String>(jsonParam, headers); // POST方式请求 ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.POST, entity, String.class); if(responseEntity == null){ return null; } return responseEntity.getBody().toString(); } }
三、通过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 }