获取url上的数据
一、添加Maven依赖
1、http依赖
<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5</version> </dependency>
2、commons依赖
<dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-io</artifactId> <version>1.3.2</version> </dependency>
3、json依赖
<dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.29</version> </dependency>
二、创建httpclient对象
CloseableHttpClient httpclient = HttpClients.createDefault();
三、HttpGet方法打开url,设置请求配置,并执行Get方法
HttpGet httpGet = new HttpGet(url);//url请求路径 RequestConfig config = RequestConfig.custom().setConnectTimeout(30000) .setConnectionRequestTimeout(30000).build(); httpGet.setConfig(config); CloseableHttpResponse response = httpclient.execute(httpGet);//获取响应对象
四、判断响应内容,并进行数据处理
1、判断响应
if (null == response || null == response.getStatusLine() || null == response.getEntity()) { logger.error("get response error, and get response null {}", JSON.toJSONString(response)); return null; } HttpEntity entry = response.getEntity();//获取响应内容 if (null == entry || !entry.isStreaming()) { logger.error("get data error, the return entry is null {} / or / entry is not streaming {}", JSON.toJSONString(response), entry.isStreaming()); }
2、读取响应内容
StringWriter writer = new StringWriter(); IOUtils.copy(entry.getContent(), writer, "UTF-8"); JSON.parseObject(writer.toString());//获取json数据
向url发送参数
一、二同上
三、HttpPost方法打开url,设置请求配置,并执行Post方法
HttpPost request = new HttpPost(url); StringEntity params = new StringEntity(body.toJSONString()); request.setEntity(params); request.setHeader("Content-type", "application/json;charset=UTF-8"); HttpResponse response = httpClient.execute(request);
JSONObject result = JSON.parseObject(JSON.toJSONString(response.getStatusLine()));
四、判断响应内容,并进行数据处理
if(!result.containsKey("reasonPhrase") || !result.containsKey("statusCode") || 0!="OK".compareTo(result.getString("reasonPhrase")) || 200!=result.getInteger("statusCode") ){//请求失败
}