HttpClient封装 get请求和post请求

通过HttpClent,如果系统间需要通信,则我们只需要提供给它这个APIService类,再告诉它调用的URL,以及各参数的含义。调用这些方法,返回的JSON数据自己做处理便可以了。这样就实现了系统之间的通信。 

结果返回类: 

package com.itheima.httpclient;

public class HttpResult {
	private Integer code;//响应状态码
	
	private String body;//响应的内容
	
	

	public HttpResult(Integer code, String body) {
		super();
		this.code = code;
		this.body = body;
	}

	public HttpResult() {
		super();
	}

	public Integer getCode() {
		return code;
	}

	public void setCode(Integer code) {
		this.code = code;
	}

	public String getBody() {
		return body;
	}

	public void setBody(String body) {
		this.body = body;
	}
	
	
}

封装HttpClient
 

public class APIService {
	// 1.不带参数的GET请求
	public HttpResult doget(String url) throws Exception {
		return doGet(url, null);
	}

	// 2.带参数的GET请求
	// 要返回http状态码以及响应的内容
	public HttpResult doGet(String url, Map<String, Object> map) throws Exception {
		// 1.创建httpclient对象
		CloseableHttpClient httpClient = HttpClients.createDefault();
		// 2.创建httget请求
		// 创建uribuilder 构建Url 及设置参数
		URIBuilder uriBuilder = new URIBuilder(url);
		// 循环遍历参数集合 设置参数
		// 判断如果map不为空
		if (map != null) {
			for (Map.Entry<String, Object> entry : map.entrySet()) {
				uriBuilder.setParameter(entry.getKey(), entry.getValue().toString());
			}
		}
		HttpGet httpGet = new HttpGet(uriBuilder.build());
		// 3.执行请求(发送请求)
		CloseableHttpResponse response = httpClient.execute(httpGet);
		// 4.接收响应内容,进行解析 封装到httpresult
		// 内容有的时候
		Integer code = response.getStatusLine().getStatusCode();// 响应的状态码
		if (response.getEntity() != null) {
			String body = EntityUtils.toString(response.getEntity(), "utf-8");// 获取响应的内容,转换成字符串
			HttpResult result = new HttpResult(code, body);
			return result;
		} else {
			HttpResult result = new HttpResult(code, null);
			return result;
		}
	}

	// 3.不带参数的POST请求
	public HttpResult doPost(String url) throws Exception{
		return doPost(url,null);
	}
	
	// 4.带参数的POST请求
	public HttpResult doPost(String url, Map<String, Object> map) throws Exception {

		// 1.创建httpclient
		CloseableHttpClient httpClient = HttpClients.createDefault();
		// 2.创建httppost请求
		HttpPost httpPost = new HttpPost(url);
		// 3.构建参数的列表
		//判断参数不为空的情况
		if (map != null) {
			List<NameValuePair> params = new ArrayList<>();
			// 遍历集合 构建参数列表
			for (Map.Entry<String, Object> entry : map.entrySet()) {
				params.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
			}
			// 4.创建form表单传递参数的实体对象
           //new UrlEncodedFormEntity(params, "utf-8") 解决服务端中文乱码问题
			UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, "utf-8");

			// 设置httpost请求的实体对象
			httpPost.setEntity(entity);
			

		}
		// 5.执行请求
		CloseableHttpResponse response = httpClient.execute(httpPost);
		// 6.接收响应 封装到httpresult中
		// 内容有的时候
		Integer code = response.getStatusLine().getStatusCode();// 响应的状态码
		if (response.getEntity() != null) {
			String body = EntityUtils.toString(response.getEntity(), "utf-8");// 获取响应的内容,转换成字符串
			HttpResult result = new HttpResult(code, body);
			return result;
		} else {
			HttpResult result = new HttpResult(code, null);
			return result;
		}
	}

}

通过此类,可以获取系统信息,也可以通过调用系统的某些请求,实现数据修改
例1:get方式请求  http://localhost:8081/item/list?page=1&rows=30  获取商品信息
 

public class MyDoGet {

	public static void main(String[] args) {
		
		CloseableHttpClient httpClient = HttpClients.createDefault();
		
		HttpGet httpGet = new HttpGet("http://localhost:8081/item/list?page=1&rows=30");
		
		CloseableHttpResponse response = null;
		try {
			 response = httpClient.execute(httpGet);
			 
			 if(response.getStatusLine().getStatusCode() == 200){
				 String content = EntityUtils.toString(response.getEntity(), "UTF-8");
				 System.out.println(content.length());
				 
				
				 
				 FileUtils.writeStringToFile(new File("content.txt"), content);
			 }
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			if(response!=null){
				try {
					response.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			
			try {
				httpClient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}

}

处理请求的Controller,@ResponseBody 返回的是json格式的数据

@Controller
public class ItemController{
	
	@Autowired
	private ItemService itemService;
	
	@RequestMapping(value="item/list",method=RequestMethod.GET)
	@ResponseBody
	public EasyUIDataGridResult getItemList(Integer page,Integer rows){
		
		if(page == null){
			page = 1;
		}
		
		if(rows == null){
			rows = 30;
		}
		
		EasyUIDataGridResult data = itemService.getItemList(page, rows);
		return data;
	}
}

 

结果:返回的json数据

例2,post请求 http://localhost:8081/item/save 保存商品数据
 

public class MyDoPostParam {

	public static void main(String[] args) throws Exception {
		
		CloseableHttpClient httpClient = HttpClients.createDefault();
		
        HttpPost httpPost = new HttpPost("http://localhost:8081/item/save");
      
		
        List<NameValuePair> parameters = new ArrayList<NameValuePair>(0);
        parameters.add(new BasicNameValuePair("title","新增的title"));
        parameters.add(new BasicNameValuePair("price", "1111"));
        parameters.add(new BasicNameValuePair("num", "1111"));
        parameters.add(new BasicNameValuePair("sellPoint", "1111"));
        parameters.add(new BasicNameValuePair("cid", "560"));

        
        /*之前写成 UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters);
         * 服务端存在中文乱码问题
         */
        //解决服务端中文乱码问题
        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters,"UTF-8");
        
        httpPost.setEntity(formEntity);
        
        
        
        CloseableHttpResponse response = null;
        try {
			 response = httpClient.execute(httpPost);
			 
			 if(response.getStatusLine().getStatusCode()==200){
				 
				 String content = EntityUtils.toString(response.getEntity(),"UTF-8");
				 System.out.println(content);
			 }else{
				 System.out.println(response.getStatusLine().getStatusCode());
				 
				 String reson = response.getStatusLine().getReasonPhrase();
				 System.out.println(reson);
			 }
			 
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			if(response!=null){
				response.close();
			}
			
			httpClient.close();
		}
        
	}

}

对应的Controller

@RequestMapping("/item/save")
	@ResponseBody
	public TaotaoResult saveItem(TbItem item, String desc) {
		
		TaotaoResult result = itemService.saveItem(item, desc);
		return result;
	}

SpringMvc框架,会将请求的参数自动封装到 TbItem item 对应的属性中,所以 HttpPost 封装的参数要看TbItem中的属性,
例如        parameters.add(new BasicNameValuePair("title","新增的title"));

结果:数据库成功添加

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值