1、请求第三方系统时,抛Invalid Http response异常,定位发现接口返回code为-1,查看url的源码,发现如果code为-1,则抛出该异常
if (var33 == -1){
throw new IOException("Invalid Http response");
}
2、因此就需要让接口自定义返回200,再读取数据;
继承HttpURLConnection重写方法
public class MyHttpURLConnection extends HttpURLConnection {
protected MyHttpURLConnection(URL url, Handler handler) throws IOException {
super(url, handler);
}
public MyHttpURLConnection(URL url, String s, int i) throws IOException {
super(url, s, i);
}
public MyHttpURLConnection(URL url, Proxy proxy) throws IOException {
super(url, proxy);
}
protected MyHttpURLConnection(URL url, Proxy proxy, Handler handler) throws IOException {
super(url, proxy, handler);
}
public int getResponseCode() throws IOException {
return 200;
}
}
继承sun.net.www.protocol.http.Handler重写openConnection方法,其中 return new MyHttpURLConnection(url,proxy, this);为上面重新的方法
public class MyHandler extends Handler {
@Override
protected URLConnection openConnection(URL url, Proxy proxy) throws IOException {
return new MyHttpURLConnection(url,proxy, this);
}
}
3、调用接口并读取数据, URL realUrl = new URL(null, url,new MyHandler());
public static String postBank(String url, String body) {
StringBuilder rest=new StringBuilder();
OutputStream out= null;
BufferedReader br= null;
try {
URL realUrl = new URL(null, url,new MyHandler());
// 打开和URL之间的连接
HttpURLConnection conn= (HttpURLConnection) realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection","keep-Alive");
// 建立实际的连接
conn.setRequestProperty("Content-Type","application/json");
// 输入 输出 都打开
conn.setDoOutput(true);
conn.setDoInput(true);
//开始连接
conn.connect();
// 传递参数 流的方式
out=conn.getOutputStream();
out.write(body.getBytes());
out.flush();
// 读取数据
br=new BufferedReader(new InputStreamReader(conn.getInputStream(),"utf-8"));
String line = null;
while (null != (line=br.readLine())){
rest.append(line);
}
log.info("====烟台银行返回结果为=>>>{}", rest);
return rest.toString();
} catch (Exception e) {
log.info("发送post请求出现异常!" + e);
e.printStackTrace();
} finally {// 使用finally块来关闭输入流
try {
if (out != null) {
out.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return null;
}