欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android下通过httpClient发送GET和POST请求的实例代码

程序员文章站 2023-11-21 23:54:22
复制代码 代码如下:       public class httputil {  &nbs...

复制代码 代码如下:

       public class httputil {

    public static string senddatabyhttpclientget(string path,string name,string pass){
        string result = "";
        //1.获取到一个浏览器
        httpclient client = new defaulthttpclient();
        //2.准备请求的地址
        try {
            string arg1 = urlencoder.encode(name, "utf-8");
            string arg2 = urlencoder.encode(pass, "utf-8");
            httpget httpget = new httpget(path+"?name="+arg1+"&pass="+arg2);

            //3.敲回车发请求
            httpresponse resp = client.execute(httpget);
            //状态码
            int code = resp.getstatusline().getstatuscode();
            if(code==200){
                //resp.getentity().getcontent();
                result = entityutils.tostring(resp.getentity(),"utf-8");
            }
        } catch (exception e) {
            e.printstacktrace();
        }
        return result;
    }

    public static string senddatabyhttpclientpost(string path,string name,string pass){
        string result = "";
        //1获取到一个浏览器
        httpclient client = new defaulthttpclient();

        //2.准备要请求的数据类型
        httppost httppost = new httppost(path);
        try {
            //键值对  namevaluepair
            list<namevaluepair> params = new arraylist<namevaluepair>();
            params.add(new basicnamevaluepair("name",name));
            params.add(new basicnamevaluepair("pass", pass));
            urlencodedformentity entity = new urlencodedformentity(params, "utf-8");
            //3.设置post请求数据实体
            httppost.setentity(entity);
            //4.发送数据给服务器
            httpresponse resp = client.execute(httppost);
            int code = resp.getstatusline().getstatuscode();
            if(code==200){
                result = entityutils.tostring(resp.getentity(),"utf-8");
            }
        } catch (exception e) {
        }
        return result;
    }

}