最近做一个使用httpclient传输json格式参数的接口,使用spring定时器定时触发调用。本来感觉一个简单的小程序,但是上线之后遇到了很奇葩的问题,运行一段时间后spring定时器莫名的死掉了,然后重启服务,几天之后又死掉了。当时第一感觉是不是数据库连接没关闭,导致程序死掉,检查代码连接都正常关闭了。重新启动项目,一天之后定时器又死掉了,又去检查spring定时器,配置都没啥问题。一直把怀疑的方向放在了spring定时器方面,没想到问题其实出在httpclient调用上。去百度httpclient的用法,用法和我写的没有什么太大区别。偶然间看到一篇文章(https://blog.csdn.net/u011191463/article/details/78664896)是说httpclient超时设置的,看后茅塞顿开。因为没有给httpclient调用设置超时时间,导致程序调用超时之后无法响应而死掉。
附上代码,以作警戒!
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import net.sf.json.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
public void SendHttp(String wlanTrouble,String telTrouble,String itvTrouble,String diagnosisDate){
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,60000);//连接时间
httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,60000);//数据传输时间
final String CONTENT_TYPE_TEXT_JSON = "text/json";
String HttpUrl="http://192.168.202.223:7807/openit/class_7?ServiceName=DiagnosisCountUpload&ServiceVer=1.0&Consumer=112IVR";
HttpPost httppost = new HttpPost(HttpUrl);
try {
String req = "{\"diagnosis\": {\"wlanTrouble\": \""+wlanTrouble+"\",\"telTrouble\": \""+telTrouble+"\",\"itvTrouble\": \""+itvTrouble+"\"},\"diagnosisDate\":\""+diagnosisDate+"\"}";
httppost.setHeader("Content-Type", "application/json;charset=UTF-8");
StringEntity se = new StringEntity(req);
se.setContentType(CONTENT_TYPE_TEXT_JSON);
httppost.setEntity(se);
HttpResponse response = httpclient.execute(httppost);
if (response.getStatusLine().getStatusCode() == 200) {
/*读返回数据*/
String conResult = EntityUtils.toString(response.getEntity());
JSONObject sobj = new JSONObject();
sobj = sobj.fromObject(conResult);
String code= sobj.getString("resultCode");
String result = sobj.getString("resultMsg");
logger.info("正常返回的code:"+code +"正常返回的info:"+result);
} else {
String err = response.getStatusLine().getStatusCode()+"";
/*异常返回数据读取*/
String conResult = EntityUtils.toString(response.getEntity());
logger.info("异常返回值是:"+conResult);
JSONObject sobj = new JSONObject();
sobj = sobj.fromObject(conResult);
logger.info("异常返回转换成json后的值是:"+conResult);
String err_code= sobj.getString("errCode");
String err_desc = sobj.getString("errMessage");
}
} catch (Exception e) {
e.printStackTrace();
logger.info("请求异常,异常信息是:"+e.getMessage());
}
}