用Java访问第三方接口时报400,打断点查看时在getInputStream()方法执行时抛出了异常
解决:判断响应码getResponseCode()不是200,201,202的话,使用getErrorStream()而不是直接getInputStream()
/**
* 获取url网址返回的数据内容
* @param urlStr
* @return
*/
public static String loadURL(String urlStr){
try{
URL url = new URL(urlStr);
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.connect();
InputStream inputStream;
//--------------------**判断**----------------------
if (urlConnection.getResponseCode() != HttpURLConnection.HTTP_OK
||urlConnection.getResponseCode() != HttpURLConnection.HTTP_CREATED
||urlConnection.getResponseCode() != HttpURLConnection.HTTP_ACCEPTED ) {
inputStream = urlConnection.getErrorStream();
}
else{
inputStream = urlConnection.getInputStream();
}
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
StringBuffer sbf = new StringBuffer();
String temp = null;
while ((temp = br.readLine()) != null) {
sbf.append(temp);
sbf.append("\r\n");
}
String result = sbf.toString();
//ConvertToString(inputStream);
return result;
}catch(IOException e){
e.printStackTrace();
return null;
}
}