基于\httpcomponents-client-4.5.5需要引入相关jar包如下:
必须导入commons-logging-1.2.jar,否则会提示
json api接口地址:
https://www.bejson.com/knownjson/webInterface/
本例用了百度上的那个接口
测试代码:
1 import org.apache.http.HttpStatus; 2 import org.apache.http.client.config.RequestConfig; 3 import org.apache.http.client.methods.CloseableHttpResponse; 4 import org.apache.http.client.methods.HttpGet; 5 import org.apache.http.client.methods.HttpPost; 6 import org.apache.http.entity.StringEntity; 7 import org.apache.http.impl.client.CloseableHttpClient; 8 import org.apache.http.impl.client.HttpClients; 9 import org.apache.http.util.EntityUtils; 10 11 12 public class HttpServletUtil { 13 public static void main(String args[]) throws Exception{ 14 15 HttpServletUtil httpServletUtil = new HttpServletUtil(); 16 String url = "http://baike.baidu.com/api/openapi/BaikeLemmaCardApi?"; 17 String params = "scope=103&format=json&appid=379020&bk_key=关键字&bk_length=600"; 18 String s = HttpServletUtil.doPost(params, url); 19 System.out.println(s); 20 } 21 22 23 public static String doPost(String params, String url) throws Exception { 24 String result = null; 25 CloseableHttpClient httpclient = HttpClients.createDefault(); 26 RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(5000).build(); 27 HttpPost httpPost = new HttpPost(url); 28 StringEntity entity = new StringEntity(params.toString(), "utf-8"); 29 httpPost.setEntity(entity); 30 //设置请求和传输超时时间 31 httpPost.setConfig(requestConfig); 32 CloseableHttpResponse httpResp = httpclient.execute(httpPost); 33 try { 34 int statusCode = httpResp.getStatusLine().getStatusCode(); 35 // 判断是够请求成功 36 if (statusCode == HttpStatus.SC_OK) { 37 System.out.println("状态码:" + statusCode); 38 System.out.println("请求成功!"); 39 // 获取返回的数据 40 result = EntityUtils.toString(httpResp.getEntity(), "UTF-8"); 41 } else { 42 System.out.println("状态码:" 43 + httpResp.getStatusLine().getStatusCode()); 44 System.out.println("HttpPost方式请求失败!"); 45 } 46 } finally { 47 httpResp.close(); 48 httpclient.close(); 49 } 50 return result; 51 } 52 53 /*public static String doGet(String url) throws Exception{ 54 String result = null; 55 httpclient = HttpClients.createDefault(); 56 HttpGet httpGet = new HttpGet(url); 57 //设置请求和传输超时时间 58 //httpGet.setConfig(requestConfig); 59 CloseableHttpResponse httpResp = httpclient.execute(httpGet); 60 try { 61 int statusCode = httpResp.getStatusLine().getStatusCode(); 62 // 判断是够请求成功 63 if (statusCode == HttpStatus.SC_OK) { 64 System.out.println("状态码:" + statusCode); 65 System.out.println("请求成功!"); 66 // 获取返回的数据 67 result = EntityUtils.toString(httpResp.getEntity(), "UTF-8"); 68 } else { 69 System.out.println("状态码:" 70 + httpResp.getStatusLine().getStatusCode()); 71 System.out.println("HttpGet方式请求失败!"); 72 } 73 } finally { 74 httpResp.close(); 75 httpclient.close(); 76 } 77 return result; 78 }*/ 79 }
请求成功后如下