今天在做第三方接口的调用时候,出现了一个非常奇怪的问题,那就是在本地tomcat7的环境下正常,jdk版本一样,但是服务器上是tomcat9,然后总是出现异常,这也太狗血了吧。于是乎,只能硬着头皮去解决。
情景:原先采用的是HttpURLConnection这个方法,tomcat7上完美运行。然而tomcat9上,我无论怎么样修改编码,响应头,都不行,(狗头保命)
顺便把之前的代码贴上来,看有不有大神知道怎么解!输入参数param是已经json序列化后的字符串。
public static String sendPost(String url,String param){
OutputStreamWriter out =null;
BufferedReader reader = null;
String response = "";
//创建连接
try {
URL httpUrl = null; //HTTP URL类 用这个类来创建连接
//创建URL
httpUrl = new URL(url);
//建立连接
HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
conn.setRequestProperty("connection", "keep-alive");
conn.setUseCaches(false);//设置不要缓存
conn.setInstanceFollowRedirects(true);
conn.setDoOutput(true);
conn.setDoInput(true);
// conn.getConnectTimeout();
// conn.setConnectTimeout(60000);
conn.connect();
//POST请求
out = new OutputStreamWriter(
conn.getOutputStream());
out.write(param);
out.flush();
//读取响应
reader = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
String lines;
while ((lines = reader.readLine()) != null) {
lines = new String(lines.getBytes(), "utf-8");
response+=lines;
}
reader.close();
// 断开连接
conn.disconnect();
} catch (Exception e) {
System.out.println("发送 POST 请求出现异常!"+e);
e.printStackTrace();
}
//使用finally块来关闭输出流、输入流
finally{
try{
if(out!=null){
out.close();
}
if(reader!=null){
reader.close();
}
}
catch(IOException ex){
ex.printStackTrace();
}
}
return response;
}
以上的方法总是有问题,可能是tomcat的http类有些许差异,tomcat9和tomcat7不一样。
绞尽脑汁。对,用这个成语,很贴切。哈哈哈哈。
最后,我还是用上了httpclient方法,这个就比较好了,对tomcat版本没要求,都是兼容的。也解决了我的问题,美滋滋。也把代码贴出来,分享给大家。
//(post请求的json.httpclient参数形式)
public static String sendPost1(String url,String param) throws IOException{
String response = null;
try {
CloseableHttpClient httpclient = null;
CloseableHttpResponse httpresponse = null;
try {
httpclient = HttpClients.createDefault();
HttpPost httppost = new HttpPost(url);
StringEntity stringentity = new StringEntity(param,
ContentType.create("text/json", "UTF-8"));
httppost.setEntity(stringentity);
httpresponse = httpclient.execute(httppost);//关键一步
response = EntityUtils
.toString(httpresponse.getEntity(),"utf-8");//加上utf-8参数防止中文乱码
System.out.println(response);
} finally {
if (httpclient != null) {
httpclient.close();
}
if (httpresponse != null) {
httpresponse.close();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
就这么简单几步,解决了我的问题。
希望遇到同样的问题的小伙伴可以少走弯路,如有问题,可以进行探讨,并指出。