Android使用httpPost向服务器发送请求的方法
本文实例讲述了Android使用httpPost向服务器发送请求的方法。分享给大家供大家参考,具体如下:
importjava.util.List; importorg.apache.http.HttpEntity; importorg.apache.http.HttpResponse; importorg.apache.http.NameValuePair; importorg.apache.http.client.HttpClient; importorg.apache.http.client.entity.UrlEncodedFormEntity; importorg.apache.http.client.methods.HttpPost; importorg.apache.http.conn.ConnectTimeoutException; importorg.apache.http.impl.client.DefaultHttpClient; importorg.apache.http.params.CoreConnectionPNames; importorg.apache.http.protocol.HTTP; importorg.apache.http.util.EntityUtils; importandroid.util.Log; publicclassRequestByHttpPost{ publicstaticStringTIME_OUT="操作超时"; publicstaticStringdoPost(List<NameValuePair>params,Stringurl)throwsException{ Stringresult=null; //新建HttpPost对象 HttpPosthttpPost=newHttpPost(url); //设置字符集 HttpEntityentity=newUrlEncodedFormEntity(params,HTTP.UTF_8); //设置参数实体 httpPost.setEntity(entity); //获取HttpClient对象 HttpClienthttpClient=newDefaultHttpClient(); //连接超时 httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,30000); //请求超时 httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,30000); try{ //获取HttpResponse实例 HttpResponsehttpResp=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(ConnectTimeoutExceptione){ result=TIME_OUT; } returnresult; } }
可以直接用的完整类。
希望本文所述对大家Android程序设计有所帮助。