您的位置:首页 > 理论基础 > 计算机网络

(一)HttpURLConnection之Get请求(解决乱码)

2014-08-27 16:46 281 查看
public static String executeHttpGet() {
String result = null;
URL url = null;
HttpURLConnection connection = null;
InputStreamReader in = null;
try {
url = new URL(
"http://api.showji.com/Locating/www.show.ji.c.o.m.aspx?m=18766581234&output=json&callback=querycallback×tamp=1409020493933");
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("GET");
connection.setRequestProperty("Content-type", "text/html");
connection.setRequestProperty("Accept-Charset", "UTF-8");
connection.setRequestProperty("contentType", "UTF-8");

if(connection.getResponseCode()== HttpURLConnection.HTTP_OK){
in = new InputStreamReader(connection.getInputStream(),"UTF-8");
BufferedReader bufferedReader = new BufferedReader(in);

StringBuffer stringBuffer = new StringBuffer();
String line = null;
while ((line = bufferedReader.readLine()) != null) {
stringBuffer.append(line);
}
result = stringBuffer.toString();
}
else{
result="网络连接错误";
}

} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
if (in != null) {
try {
in.close();
} catch (Exception e2) {
// TODO: handle exception
e2.printStackTrace();
}
}
}
return result;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: