java笔记2-http调用
1.http调用
1.含义
javahttp调用的功能(在我看来)主要是实现一个客户端的功能,它使得我们的程序近似于一个浏览器,通过http请求和其他url进行通信,通过get请求去获取网站数据,或者通过post请求将本地的数据发送至某个位置(我尝试的功能是将数据包以json格式的形式发送至服务器)
2.主要工具
javahttp调用一般采取调用第三方接口的形式。主要有以下工具可以参考:
1、通过JDK网络类Java.net.HttpURLConnection;
2、通过common封装好的HttpClient;
3、通过Apache封装好的CloseableHttpClient;
4、通过SpringBoot-RestTemplate;
这次主要记录一下HttpClient包的使用
2.HttpClient包
1.maven依赖
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>2.0.23</version> </dependency>
<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.14</version> </dependency>
|
2.基本使用
1.URIbuilder
传入一个网址的string,构造一个URI
1 2 3 4 5 6
| URIBuilder uriBuilder = new URIBuilder(url); uriBuilder.setFragment("111"); uriBuilder.setUserInfo("222", "333"); uriBuilder.setCharset(new GBK());
uriBuilder.clearParameters();
|
2.修改URI
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| String url = "http://ads-mediation.internal.zkq.sg/media/app?m=102909"; URIBuilder uriBuilder = new URIBuilder(url); ArrayList<NameValuePair> objects = new ArrayList<>(); NameValuePair m = new BasicNameValuePair("m", "1"); objects.add(m); ArrayList<NameValuePair> objects1 = new ArrayList<>(); NameValuePair m1 = new BasicNameValuePair("m", "8"); objects1.add(m1); uriBuilder.setParameters(objects); uriBuilder.addParameters(objects1); System.out.println(uriBuilder.build());
|
3.基本步骤
- 创建HttpClient对象。
- 创建请求方法的实例,并指定请求URL。依据请求类型分别创建HttpGet对象或者HttpPost对象
- 修改发送参数,HttpGet和HttpPost对象都拥有setParams方法,HttpPost拥有setEntity方法来设置请求参数。
- 调用execute方法发送请求,会收到HttpResonse返回。
- 调用HttpResponse的getAllHeaders,getHeaders等方法获取响应头。getEntity方法可以获得实体对象。
- 最后一定要释放连接。
4.两个实例
1.基本get用法。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
| public class HttpClientDemo { public void getRequest(String url) throws URISyntaxException, IOException { CloseableHttpClient client = HttpClients.createDefault(); URIBuilder uriBuilder = new URIBuilder(url); uriBuilder.addParameter("account", "123"); uriBuilder.addParameter("password", "123"); HttpGet httpGet = new HttpGet(uriBuilder.build()); httpGet.setHeader("Authorization", "Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0"); RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000) .setConnectionRequestTimeout(35000) .setSocketTimeout(60000) .build(); httpGet.setConfig(requestConfig); CloseableHttpResponse response = client.execute(httpGet); int statusCode = response.getStatusLine().getStatusCode(); System.out.println(statusCode); HttpEntity entity = response.getEntity(); String str = EntityUtils.toString(entity); System.out.println(str); response.close(); client.close(); } }
public ResponseBase doGet(String url) { try { HttpGet request = new HttpGet(url); HttpClient httpClient = HttpClientBuilder.create().build(); HttpResponse httpResponse = httpClient.execute(request); int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { throw new DIYException(setResultError("发送GET请求失败").toString()); } HttpEntity responseHttpEntity = httpResponse.getEntity(); String string = EntityUtils.toString(responseHttpEntity, "utf-8"); return setResultSuccessData(string, "发送GET请求成功"); } catch (Exception e) { log.error("发送GET请求异常:" + e.getMessage()); throw new DIYException(setResultError("发送GET请求异常:" + e.getMessage()).toString()); }
|
2.基本post用法。(数据包为json格式)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| public boolean PostMsg(String url, JSONObject jsonParam) { HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); HttpPost post = new HttpPost(url); try (CloseableHttpClient closeableHttpClient = httpClientBuilder.build()) { StringEntity entity = new StringEntity(jsonParam.toString(),"utf-8"); entity.setContentEncoding("UTF-8"); entity.setContentType("application/json"); post.setEntity(entity); HttpResponse resp = closeableHttpClient.execute(post); int statusCode = resp.getStatusLine().getStatusCode(); System.out.println("statuscode : "+statusCode); HttpEntity responsehttpentity = resp.getEntity(); String statuscontent = EntityUtils.toString(responsehttpentity,"utf-8"); System.out.println("statusentity : " + statuscontent);
} catch (IOException e) { e.printStackTrace(); return false; } return true; }
|
3.连接池
节省内存使用:无需每一次请求都创建一个httpClient,以连接池的形式管理,创建一个后台线程用于资源释放与回收。
(开个坑,这一块没有看完)
[(93条消息) 高性能HttpClient_staticstone的博客-CSDN博客](https://blog.csdn.net/staticstone/article/details/128818681#:~:text=%2F%2F得到客户段响应的实体内容 HttpEntity responseHttpEntity %3D httpResponse.getEntity ()%3B String string,setResultSuccessData (string%2C “发送GET请求成功”)%3B } catch (Exception e) {)