发送get请求 获取输入流 ,发送get请求 获取响应字符串

/**
* 发送get请求  获取输入流 
* @param uri  完整的请求资源路径
* @return
* @throws MalformedURLException 
* @throws IOException 
*/
public static InputStream getInputStream(String uri) throws IOException{
//1.  URL
URL url = new URL(uri);
//2. openConnection
HttpURLConnection conn=(HttpURLConnection) url.openConnection();
//3. GET
conn.setRequestMethod("GET");
//4.  getInputStream
InputStream is = conn.getInputStream();
return is;
}
/**
* 发送get请求 获取响应字符串
* @param uri
* @return
* @throws IOException 
* @throws MalformedURLException 
*/
public static String getString(String uri) throws MalformedURLException, IOException{
InputStream is = getInputStream(uri);
//把输入流中的内容转成字符串
StringBuilder sb = new StringBuilder();
String line=null;
BufferedReader reader=new BufferedReader(new InputStreamReader(is));
while((line=reader.readLine())!=null){
sb.append(line);
}
String respText=sb.toString();
return respText;
}

你可能感兴趣的:(发送get请求 获取输入流 ,发送get请求 获取响应字符串)