首页 > 编程知识 正文

java开发restful接口实例,httpclient爬虫

时间:2023-05-03 12:58:38 阅读:165364 作者:4077

本节总结了使用http客户端访问外部接口的用法。 后期发现什么缺陷的话就更改。 欢迎读者指出这种方法的缺点。

首先,创建返回实体。

公共类http result {

//响应的状态代码

私有代码;

//响应的响应体

私有字符串主体;

publichttpresult(intcode,String body ) {

this.code=代码;

this.body=body;

}

省去get/set

}

创建http客户端util :

公共类http客户端实用程序{

privatestaticcloseablehttpclienthttpclient=http clients.create default (; 用静态实现单实例。 如果这里不完整,成为多线程,就会出现问题。

//*

*带参数的get请求

*

* @param url

* @param map

* @return

* @throws Exception

*/

publicstatichttpresultdoget (string URL,Map map ) throws Exception { )。

声明URIBuilder

uribuilderuribuilder=new uri builder (URL;

//判断参数映射是否为非空

if (地图!=null ) {

//导线参数

映射.条目条目:映射. entryset ) }

//设定参数

uri builder.set parameter (entry.getkey ),entry.getValue ) ).toString );

}

}

创建//2httpget对象相当于设置url请求地址

http get http get=new http get (uri builder.build () );

利用//3 http客户端进行httpGet,相当于按下回车,开始请求

closeablehttpresponseresponse=http client.execute (http get );

分析//4结果,封装并返回对象httpResult,相当于显示相应的结果

//状态代码

//response.get statusline (.get status code );

//响应、字符串、response.getEntity ) )为空时,以下代码将出错,因此在分析之前判断为非空

//entity utils.tostring (response.get entity ),' UTF-8 ' );

HttpResult httpResult=null;

//分析数据封装HttpResult

if(response.getentity )!=null ) {

http result=newhttpresult (response.get statusline ().getStatusCode )、

entity utils.tostring (response.get entity ),' UTF-8 ' );

} else {

http result=newhttpresult (response.get statusline ().getStatusCode ),'');

}

//返回

返回http结果;

}

//*

*无参数的get请求

*

* @param url

* @return

* @throws Exception

*/

publicstatichttpresultdoget (string URL ) throws Exception {

HTPresulthttpresult=doget(URL,null );

返回http结果;

}

//*

*带参数的开机自检请求

*

* @param url

* @return

* @throws Exception

*/

publicstatichttpresultdopost (str

ing url, Map reqMap, Map headersMap) throws Exception {

// 声明httpPost请求

HttpPost httpPost = new HttpPost(url);

for (Map.Entry entry: headersMap.entrySet())

httpPost.addHeader(entry.getKey(), entry.getValue());

// 判断map不为空

if (reqMap != null) {

// 创建form表单对象

StringEntity formEntity = new StringEntity(JSON.toJSONString(reqMap), "UTF-8");

// 把表单对象设置到httpPost中

httpPost.setEntity(formEntity);

}

// 使用HttpClient发起请求,返回response

CloseableHttpResponse response = httpClient.execute(httpPost);

// 解析response封装返回对象httpResult

HttpResult httpResult = null;

if (response.getEntity() != null) {

httpResult = new HttpResult(response.getStatusLine().getStatusCode(),

EntityUtils.toString(response.getEntity(), "UTF-8"));

} else {

httpResult = new HttpResult(response.getStatusLine().getStatusCode(), "");

}

// 返回结果

return httpResult;

}

/**

* 不带参数的post请求

*

* @param url

* @return

* @throws Exception

*/

public static HttpResult doPost(String url) throws Exception {

HttpResult httpResult = doPost(url, null,null);

return httpResult;

}

/**

* 带参数的Put请求

*

* @param url

* @param map

* @return

* @throws Exception

*/

public static HttpResult doPut(String url, Map map) throws Exception {

// 声明httpPost请求

HttpPut httpPut = new HttpPut(url);

// 判断map不为空

if (map != null) {

// 声明存放参数的List集合

List params = new ArrayList();

// 遍历map,设置参数到list中

for (Map.Entry entry : map.entrySet()) {

params.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));

}

// 创建form表单对象

UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params, "UTF-8");

// 把表单对象设置到httpPost中

httpPut.setEntity(formEntity);

}

// 使用HttpClient发起请求,返回response

CloseableHttpResponse response = httpClient.execute(httpPut);

// 解析response封装返回对象httpResult

HttpResult httpResult = null;

if (response.getEntity() != null) {

httpResult = new HttpResult(response.getStatusLine().getStatusCode(),

EntityUtils.toString(response.getEntity(), "UTF-8"));

} else {

httpResult = new HttpResult(response.getStatusLine().getStatusCode(), "");

}

// 返回结果

return httpResult;

}

/**

* 带参数的Delete请求

*

* @param url

* @param map

* @return

* @throws Exception

*/

public static HttpResult doDelete(String url, Map map) throws Exception {

// 声明URIBuilder

URIBuilder uriBuilder = new URIBuilder(url);

// 判断参数map是否为非空

if (map != null) {

// 遍历参数

for (Map.Entry entry : map.entrySet()) {

// 设置参数

uriBuilder.setParameter(entry.getKey(), entry.getValue().toString());

}

}

// 2 创建httpGet对象,相当于设置url请求地址

HttpDelete httpDelete = new HttpDelete(uriBuilder.build());

// 3 使用HttpClient执行httpGet,相当于按回车,发起请求

CloseableHttpResponse response = httpClient.execute(httpDelete);

// 4 解析结果,封装返回对象httpResult,相当于显示相应的结果

// 状态码

// response.getStatusLine().getStatusCode();

// 响应体,字符串,如果response.getEntity()为空,下面这个代码会报错,所以解析之前要做非空的判断

// EntityUtils.toString(response.getEntity(), "UTF-8");

HttpResult httpResult = null;

// 解析数据封装HttpResult

if (response.getEntity() != null) {

httpResult = new HttpResult(response.getStatusLine().getStatusCode(),

EntityUtils.toString(response.getEntity(), "UTF-8"));

} else {

httpResult = new HttpResult(response.getStatusLine().getStatusCode(), "");

}

// 返回

return httpResult;

}

/**

* 返回常用请求头

* @return

*/

public static Map commentHeader(){

Map map = new HashMap<>();

map.put("Content-Type", "application/json");

return map;

}

}

测试一下:

package cn.xxxxxx.httpclient.test;

import java.util.HashMap;

import java.util.Map;

import org.junit.Before;

import org.junit.Test;

import cn.itcast.httpclient.APIService;

import cn.itcast.httpclient.HttpResult;

public class APIServiceTest {

// 查询

@Test

public void testGet() throws Exception {

// http://manager.aaaaaa.com/rest/item/interface/{id}

String url = "http://manager.aaaaaa.com/rest/item/interface/42";

HttpResult httpResult = HttpClientUtil.doGet(url);

System.out.println(httpResult.getCode());

System.out.println(httpResult.getBody());

}

// 查询

@Test

public void testPost() throws Exception {

//设置参数

Map reqMap = new HashMap();

reqMap.put("distCode", arsArg.getDistCode());

HttpResult httpResult = null;

try {

//RestUrlsCommons.RMDS_DISTRICT_FINDBYDISTCODE为url

//reqMap:请求参数

//HttpClientUtil.commentHeader():请求头

httpResult = HttpClientUtil.doPost(RestUrlsCommons.RMDS_DISTRICT_FINDBYDISTCODE, reqMap, HttpClientUtil.commentHeader());

} catch (Exception e) {

e.printStackTrace();

}

System.out.println(httpResult.getCode());

System.out.println(httpResult.getBody());

}

}

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。