/**
* @author Administrator
* @date 2015年12月9日 上午10:56:38
* @description 根据url获取json数据
* @parameter
* @return JsonObject数据
* @throws IOException
* @throws HttpException
*/
public void getDataByUrl(String url) throws HttpException, IOException {
//创建httpClient对象
HttpClient client = new HttpClient();
//创建post请求方法
PostMethod post = new PostMethod(url);
//设置请求超时时间
client.getHttpConnectionManager().getParams().setConnectionTimeout(30 * 1000);
//设置代理服务器的ip地址和端口
client.getHostConfiguration().setProxy("XXX.XX.XX.XXX", 8080);
//使用抢先认证
client.getParams().setAuthenticationPreemptive(true);
String responseString = null;
//设置请求头部类型
post.setRequestHeader("Content-Type","text/xml");
post.setRequestHeader(HttpMethodParams.HTTP_CONTENT_CHARSET,"utf-8");
//获取状态码
int statusCode = client.executeMethod(post);
//如果访问成功 statusCode == 200
if(statusCode == HttpStatus.SC_OK){
BufferedInputStream bis = new BufferedInputStream(post.getResponseBodyAsStream());
byte[] bytes = new byte[1024];
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int count = 0;
while((count = bis.read(bytes))!= -1){
bos.write(bytes, 0, count);
}
byte[] strByte = bos.toByteArray();
responseString = new String(strByte,0,strByte.length,"utf-8");
bos.close();
bis.close();
}
//释放链接
post.releaseConnection();
JSONObject json = JSONObject.parseObject(responseString);
//...........................
}
}
httpclient访问接口
最新推荐文章于 2022-11-16 23:23:22 发布