美文网首页androidAndroid开发程序员
Android的http两种请求方式

Android的http两种请求方式

作者: 赤赤有名 | 来源:发表于2016-05-05 08:55 被阅读429次

前言:

通过HttpGet和HttpPost向服务器提交请求,并从服务器返回结果信息。通过如下3步访问Http资源。

(1)创建HttpGet或者HttpPost对象,将要请求的URL通过构造方法传入HttpGet或HttpPost对象。

(2)使用DefaultHttpClient.execute方法发送Http Get或Http Post请求,并返回HttpResponse对象。

(3)通过HttpResponse.getEntity方法返回响应信息,并进行相应的处理。

如果使用HttpPost方法提交Http Post请求,还需要使用HttpPost.setEntity方法设置请求参数。

实例代码:Android_Http Get和Post请求 - zlfxy的专栏 - 博客频道 - CSDN.NET


http的两种请求方式:POST和GET

由于Android的SDK包含org.apache.http包,所以不用导入jar了

(1)GET方式:


String serverURL = "http://127.0.0.1/xxx/xx.jsp?username=abc;HttpGet httpRequest =newHttpGet(serverURL);                                 //建立http get联机

HttpResponse httpResponse =newDefaultHttpClient().execute(httpRequest);//发出http请求

if(httpResponse.getStatusLine().getStatusCode() == 200)

String result= EntityUtils.toString(httpResponse.getEntity());//获取相应的字符串


(2)POST方式:


String uriAPI = "http://127.0.0.1/xxx/xx.jsp";//声明网址字符串HttpPost httpRequest =newHttpPost(uriAPI);//建立HTTP POST联机List params =newArrayList ();//Post运作传送变量必须用NameValuePair[]数组储存params.add(newBasicNameValuePair("str", "I am Post String"));

httpRequest.setEntity(newUrlEncodedFormEntity(params, HTTP.UTF_8));//发出http请求HttpResponse httpResponse =newDefaultHttpClient().execute(httpRequest);

//取得http响应

if(httpResponse.getStatusLine().getStatusCode() == 200)

String strResult= EntityUtils.toString(httpResponse.getEntity());//获取字符串


相关文章

网友评论

    本文标题:Android的http两种请求方式

    本文链接:https://www.haomeiwen.com/subject/eokdrttx.html