在项目中有过这么一次要求,就是在我本次项目中要使用java调用别人的接口,使用的方式时http的get请求。请求到的数据进行处理。话不多说直接贴代码,如下
//http请求==============
protected static InputStream httpRead(String url){
Debug.info("==========Graphic httpRead come in===========");
GetMethod get = null;
try {
HttpClient hc = new HttpClient();
get = new GetMethod(url);
int statusCode = hc.executeMethod(get);
if (statusCode != HttpStatus.SC_OK) {
Debug.err("bad url");
return null;
}
return get.getResponseBodyAsStream();
} catch (Exception e) {
Debug.err(e.getMessage());
} finally {
/*if (get != null) {
get.releaseConnection();
}*/
}
return null;
}
这里有几个注意点:
1、finally的get关闭如果是单独调用在此方法里写逻辑可以这么关闭,单独抽取出来的方法关闭的话,虽然返回流了,但是此流不能用。这点特别注意
2、这段代码引用的jar包是commons-httpclient-3.1-rc1.jar
后续操作就是解析流的问题。看对方的接口给你的内容是什么格式的,然后进行处理。
这是本次的get请求,post请求后续有需要我再次整理。