67,514
社区成员
发帖
与我相关
我的任务
分享
/**
* 使用get请求以HttpClient org.apache.http请求数据
*
* @param path
* @return
* @throws IOException
* @throws ClientProtocolException
* @throws IOException
*/
public static String doGetByHttpClient(String path) throws ClientProtocolException, IOException {
HttpClient hc = new DefaultHttpClient(getHttpParams());
HttpGet request = new HttpGet(path);
System.out.println("1:============================");
// request.addHeader("Content-Type", "application/json; charset=utf-8");
HttpResponse response = hc.execute(request);
System.out.println("2:============================");
// System.out.println(response.getStatusLine().getStatusCode());
if (response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK) {
// return EntityUtils.toString(response.getEntity());
StringBuilder builder = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(
response.getEntity().getContent(), "UTF-8"));
for (String s = reader.readLine(); s != null; s = reader.readLine()) {
builder.append(s);
}
if (reader != null)
reader.close();
return builder.toString();
}
return null;
}
HttpResponse response = hc.execute(request);
时就会报错。java.net.SocketException:Connetion reset by peer。
/**
* 使用get请求以普通方式java.net请求数据
*
* @param path
* @return
*/
public static String doGetByOrdinary(String path) {
HttpURLConnection httpConn = null;
BufferedReader reader = null;
try {
URL url = new URL(path);
httpConn = (HttpURLConnection) url.openConnection();
httpConn.setRequestMethod("GET");
httpConn.setConnectTimeout(5000);
httpConn.setReadTimeout(5000);
if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
StringBuilder builder = new StringBuilder();
reader = new BufferedReader(new InputStreamReader(httpConn
.getInputStream(), "UTF-8"));
for (String s = reader.readLine(); s != null; s = reader
.readLine()) {
builder.append(s);
}
return builder.toString();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (reader != null)
reader.close();
if (httpConn != null)
httpConn.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}