基于 \ httpcomponents-client-4.5.5 需要引入相关 jar 包如下:
必须导入 commons-logging-1.2.jar, 否则会提示
json api 接口地址:
https://www.bejson.com/knownjson/webInterface/
本例用了百度上的那个接口
测试代码:
- import org.apache.http.HttpStatus;
- import org.apache.http.client.config.RequestConfig;
- import org.apache.http.client.methods.CloseableHttpResponse;
- import org.apache.http.client.methods.HttpGet;
- import org.apache.http.client.methods.HttpPost;
- import org.apache.http.entity.StringEntity;
- import org.apache.http.impl.client.CloseableHttpClient;
- import org.apache.http.impl.client.HttpClients;
- import org.apache.http.util.EntityUtils;
- public class HttpServletUtil {
- public static void main(String args[]) throws Exception {
- HttpServletUtil httpServletUtil = new HttpServletUtil();
- String url = "http://baike.baidu.com/api/openapi/BaikeLemmaCardApi?";
- String params = "scope=103&format=json&appid=379020&bk_key = 关键字 & bk_length=600";
- String s = HttpServletUtil.doPost(params, url);
- System.out.println(s);
- }
- public static String doPost(String params, String url) throws Exception {
- String result = null;
- CloseableHttpClient httpclient = HttpClients.createDefault();
- RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(5000).build();
- HttpPost httpPost = new HttpPost(url);
- StringEntity entity = new StringEntity(params.toString(), "utf-8");
- httpPost.setEntity(entity);
- // 设置请求和传输超时时间
- httpPost.setConfig(requestConfig);
- CloseableHttpResponse httpResp = httpclient.execute(httpPost);
- try {
- int statusCode = httpResp.getStatusLine().getStatusCode();
- // 判断是够请求成功
- if (statusCode == HttpStatus.SC_OK) {
- System.out.println("状态码:" + statusCode);
- System.out.println("请求成功!");
- // 获取返回的数据
- result = EntityUtils.toString(httpResp.getEntity(), "UTF-8");
- } else {
- System.out.println("状态码:" + httpResp.getStatusLine().getStatusCode());
- System.out.println("HttpPost 方式请求失败!");
- }
- } finally {
- httpResp.close();
- httpclient.close();
- }
- return result;
- }
- /*public static String doGet(String url) throws Exception{
- String result = null;
- httpclient = HttpClients.createDefault();
- HttpGet httpGet = new HttpGet(url);
- // 设置请求和传输超时时间
- //httpGet.setConfig(requestConfig);
- CloseableHttpResponse httpResp = httpclient.execute(httpGet);
- try {
- int statusCode = httpResp.getStatusLine().getStatusCode();
- // 判断是够请求成功
- if (statusCode == HttpStatus.SC_OK) {
- System.out.println("状态码:" + statusCode);
- System.out.println("请求成功!");
- // 获取返回的数据
- result = EntityUtils.toString(httpResp.getEntity(), "UTF-8");
- } else {
- System.out.println("状态码:"
- + httpResp.getStatusLine().getStatusCode());
- System.out.println("HttpGet 方式请求失败!");
- }
- } finally {
- httpResp.close();
- httpclient.close();
- }
- return result;
- }*/
- }
- View Code
请求成功后如下
来源: http://www.bubuko.com/infodetail-2497117.html