1. 程式人生 > >HttpURLConnection請求網路工具類

HttpURLConnection請求網路工具類

class NetUtile {
public static String getJson(String string) {
try {
URL url = new URL(string);
try {
// HttpURLConnection 請求
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
int responseCode = httpURLConnection.getResponseCode();
if(responseCode==200){
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String str = “”;
StringBuilder stringBuilder = new StringBuilder();
while ((str=bufferedReader.readLine())!=null){
stringBuilder.append(str);
}
return stringBuilder.toString(); // 返回值
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (MalformedURLException e) {
e.printStackTrace();
}
return “”;
}
}