java HttpClient 请求:具体代码如下:(引入的包都是io包)
方法二中的释放io资源,最开始没有在finally释放,被我们公司老大给说了,后来给修改为在finally释放。
方法一:
private static Object httpGet(String url)
{
//get请求返回结果
JSONObject jsonResult = null;
try {
DefaultHttpClient client = new DefaultHttpClient();
//发送get请求
HttpGet request = new HttpGet(url);
HttpResponse response = client.execute(request);
/**请求发送成功,并得到响应**/
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
/**读取服务器返回过来的json字符串数据**/
String strResult = EntityUtils.toString(response.getEntity());
/**把json字符串转换成json对象**/
jsonResult = JSONObject.parseObject(strResult);
url = URLDecoder.decode(url, "UTF-8");
} else {
}
} catch (IOException e) {
}
return null;
}
方法二:
publicJSONObjecthttpGet(Stringreq_url) {
StringBufferbuffer=newStringBuffer();
InputStreaminputStream=null;
HttpURLConnectionhttpUrlConn=null;
InputStreamReaderinputStreamReader=null;
BufferedReaderbufferedReader=null;
try{
URLurl=newURL(req_url);
httpUrlConn= (HttpURLConnection)url.openConnection();
httpUrlConn.setDoOutput(false);
httpUrlConn.setDoInput(true);
httpUrlConn.setUseCaches(false);
httpUrlConn.setRequestMethod("GET");
httpUrlConn.connect();
// 将返回的输入流转换成字符串
inputStream=httpUrlConn.getInputStream();
inputStreamReader=newInputStreamReader(inputStream,"utf-8");
bufferedReader=newBufferedReader(inputStreamReader);
Stringstr=null;
while((str=bufferedReader.readLine()) !=null) {
buffer.append(str);
}
}catch(Exceptione) {
LOGGER.error(e.getMessage());
}finally{
// 释放资源
try{
inputStream.close();
bufferedReader.close();
inputStreamReader.close();
}catch(IOExceptione) {
LOGGER.error(e.getMessage());
}
inputStream=null;
httpUrlConn.disconnect();
}
returnJSONObject.parseObject(buffer.toString());
}