Skip to content

Instantly share code, notes, and snippets.

@gexiangdong
Created April 24, 2019 10:03
Show Gist options
  • Save gexiangdong/209b2c49326736ae21093efd65751a27 to your computer and use it in GitHub Desktop.
Save gexiangdong/209b2c49326736ae21093efd65751a27 to your computer and use it in GitHub Desktop.
服务器返回4xx等时,读取responsebody
import java.io.*;
import java.util.*;
import java.net.*;
public class HttpGet{
public static void main(String[] argbs) throws Exception{
String url = "http://localhost:8080/";
URL obj = new URL(url);
HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
conn.setRequestProperty("Accept", "*/*");
conn.setRequestMethod("GET");
int responseCode = conn.getResponseCode();
InputStream is = conn.getErrorStream(); // 如果服务器端返回的是403等等代码,要读取返回的response body,需要从这个errorstream内读取了
if (is == null) {
is = conn.getInputStream();
}
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(is));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
is.close();
System.out.println("Response Body :\r\n" + response.toString());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment