当前位置: 移动技术网 > IT编程>移动开发>Android > Android下通过httpClient发送GET和POST请求的实例代码

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

2019年07月24日  | 移动技术网IT编程  | 我要评论

赵舒,通辽房屋出租,zhongguohehuoren

复制代码 代码如下:

       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;
    }

}

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网