HttpPost如何设置超时时间

类:org.apache.http.client.methods.HttpPost

今天一位姓申的同事问,特做记录埋汰一下波波。:)

//请求超时 httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 3000); 
//读取超时 httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,3000);
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

public class mHttpRequest {
	
	/*
	 * 发送post请求
	 * 
	 * @param posturl:接口路径
	 * @param params:模拟form表单数据
	*/
	public static void mPostForm(String posturl, List<NameValuePair> params) throws Exception
	{
		   //声明一个httppost绑定参数
		   HttpPost httppost = new HttpPost(posturl);
		   // 绑定到Entity
		   httppost.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));
		   //实例化httpclient对象
		   DefaultHttpClient httpclient = new DefaultHttpClient();
		   //请求超时
		   httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 3000);
		   //读取超时
		   httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,3000);
		   //执行请求
		   HttpResponse httpResponse =  httpclient.execute(httppost);
		   //返回状态为200
		   if(httpResponse.getStatusLine().getStatusCode() == 200){
		      // 得到应答的字符串,这也是一个 JSON 格式保存的数据 
		      String res = EntityUtils.toString(httpResponse.getEntity());  
		      // 应答生成 JSON 对象   
		      JSONObject result = new JSONObject( res);  
		      int errcode = result.getInt("errcode");
		      //String errmsg = result.getString("errmsg");
		      //返回结果
		      if(errcode==0){
		      }
		      else{
		      }
		   }
    }
		
}
发布了29 篇原创文章 · 获赞 5 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/chyercn/article/details/97273357