简单的使用httpClient之远程请求获取数据
httpClient使用非常方便,远程请求url路径获取返回数据,数据类型可以是字符串,字节数组。httpClient顾名思义,实现了http协议的客户端。值得注意的是请求之后,一定要关闭请求。
import java.io.IOException; import java.util.Map; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpException; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.methods.PostMethod; import org.springframework.stereotype.Service; import com.chinaedu.nstats.service.IServiceUtils; @Service("serviceUtils") public class ServiceUtils implements IServiceUtils { public String execute(String url){ HttpClient httpClient = new HttpClient(); GetMethod getMethod = null; getMethod = new GetMethod(url); String responseBody=null; try { int statusCode = httpClient.executeMethod(getMethod); if (statusCode != HttpStatus.SC_OK) { System.err.println("Method failed: " + getMethod.getStatusLine()); } // 读取内容 responseBody = getMethod.getResponseBodyAsString(); } catch (HttpException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally{ getMethod.releaseConnection(); } return responseBody; } public String executePostMethod(String url,Map<String,String> parames){ HttpClient httpClient = new HttpClient(); PostMethod postMethod=null; postMethod = new PostMethod(url); postMethod.addParameter("subject", parames.get("subject")); postMethod.addParameter("teacher", parames.get("teacher")); postMethod.addParameter("beginTime", parames.get("beginTime")); postMethod.addParameter("endTime", parames.get("endTime")); String responseBody=null; try { int statusCode = httpClient.executeMethod(postMethod); if (statusCode != HttpStatus.SC_OK) { System.err.println("Method failed: " + postMethod.getStatusLine()); } // 读取内容 responseBody = postMethod.getResponseBodyAsString(); } catch (HttpException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally{ postMethod.releaseConnection(); } return responseBody; } }
相关推荐
Kafka 2020-09-18
Wepe0 2020-10-30
杜倩 2020-10-29
windle 2020-10-29
minerd 2020-10-28
mengzuchao 2020-10-22
Junzizhiai 2020-10-10
bxqybxqy 2020-09-30
风之沙城 2020-09-24
kingszelda 2020-09-22
大唐帝国前营 2020-08-18
yixu0 2020-08-17
TangCuYu 2020-08-15
xiaoboliu00 2020-08-15
songshijiazuaa 2020-08-15
xclxcl 2020-08-03
zmzmmf 2020-08-03
newfarhui 2020-08-03
likesyour 2020-08-01