本文实例讲述了android使用httppost向服务器发送请求的方法。分享给大家供大家参考,具体如下:
import java.util.list; import org.apache.http.httpentity; import org.apache.http.httpresponse; import org.apache.http.namevaluepair; import org.apache.http.client.httpclient; import org.apache.http.client.entity.urlencodedformentity; import org.apache.http.client.methods.httppost; import org.apache.http.conn.connecttimeoutexception; 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 android.util.log; public class requestbyhttppost { public static string time_out = "操作超时"; public static string dopost(list<namevaluepair> params,string url) throws exception{ string result = null; // 新建httppost对象 httppost httppost = new httppost(url); // 设置字符集 httpentity entity = new urlencodedformentity(params, http.utf_8); // 设置参数实体 httppost.setentity(entity); // 获取httpclient对象 httpclient httpclient = new defaulthttpclient(); //连接超时 httpclient.getparams().setparameter(coreconnectionpnames.connection_timeout, 30000); //请求超时 httpclient.getparams().setparameter(coreconnectionpnames.so_timeout, 30000); try { // 获取httpresponse实例 httpresponse httpresp = httpclient.execute(httppost); // 判断是够请求成功 if (httpresp.getstatusline().getstatuscode() == 200) { // 获取返回的数据 result = entityutils.tostring(httpresp.getentity(), "utf-8"); log.i("httppost", "httppost方式请求成功,返回数据如下:"); log.i("result", result); } else { log.i("httppost", "httppost方式请求失败"); } } catch (connecttimeoutexception e){ result = time_out; } return result; } }
可以直接用的完整类。
希望本文所述对大家android程序设计有所帮助。
如对本文有疑问, 点击进行留言回复!!
Codeforces C. A Cookie for You (模拟 / 分类 / 贪心) (Round #654 Div.2)
DialogFragment弹窗(带黑色透明背景和不带黑色透明背景)
android 常用布局文件(LinearLayout,RelativeLayout,FrameLayout,ConstraintLayout,TableLayout)
网友评论