服务器之家

服务器之家 > 正文

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

时间:2021-02-04 15:12     来源/作者:Android开发网

复制代码 代码如下:


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

 

}

 

标签:

相关文章

热门资讯

2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全 2019-12-26
Intellij idea2020永久破解,亲测可用!!!
Intellij idea2020永久破解,亲测可用!!! 2020-07-29
背刺什么意思 网络词语背刺是什么梗
背刺什么意思 网络词语背刺是什么梗 2020-05-22
yue是什么意思 网络流行语yue了是什么梗
yue是什么意思 网络流行语yue了是什么梗 2020-10-11
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总 2020-11-13
返回顶部