问题描述
项目中使用Feign组件远程调用问题记录,本地代码执行正常,部署到服务器访问调用不了远程接口,报 feign.FeignException: status 400 reading,不太清楚是什么问题,分别用了httpclinet、resttemplate、feign,结果都失败报同一个问题,明明本地运行正常,线上就不正常了呢?
原因分析:
网上查了很多报错的原因,但是都不符合,最后用了HttpURLConnection这个api 成功解决
解决方案:
//post请求
public static <T> T doPost(String url, Object requestObj, Class<T> tClass) throws IOException {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
// 打开和URL之间的连接
HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
// 设置通用的请求属性
conn.setRequestMethod("POST");
conn.setConnectTimeout(4 * 1000);
conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(), "utf-8"));
out.println(JSON.toJSONString(requestObj));
// flush输出流的缓冲
out.flush();
InputStream is = null;
if (conn.getResponseCode() >= 400) {
is = conn.getErrorStream();
} else {
is = conn.getInputStream();
}
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(is,"utf-8"));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送 POST 请求出现异常!" + e);
e.printStackTrace();
}
//使用finally块来关闭输出流、输入流
finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
log.info("流获取的对象:---"+result);
T t = JSON.parseObject(result, tClass);
return t;
}
//get请求
public static JSONObject useGetMethod(String get_url){
try {
Map<String,Object> result = new HashMap<String,Object>();
JSONObject jsonObject=null;
URL url = new URL(get_url);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
//设置连接远程服务器的超时时间
connection.setConnectTimeout(30000);
//设置读取远程返回的数据时间
connection.setReadTimeout(30000);
connection.connect();
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
StringBuffer str = new StringBuffer();
InputStream in = connection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(in, "utf-8"));
try{
String line = "";
while((line = br.readLine()) != null) {
str.append(line);
}
} finally {
br.close();
in.close();
}
jsonObject = JSONObject.parseObject(str.toString());
// result.put("code", jsonObject.get("code"));
// result.put("data", jsonObject.get("data"));
}else{
// System.out.println("错误状态码:"+responseCode);
// result.put("code", responseCode);
// result.put("message", "异常");
}
connection.disconnect();
return jsonObject;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}