关闭

HttpClient请求

标签: 数据请求
140人阅读 评论(0) 收藏 举报
分类:

post请求

protected void getHttpClientPost(String url) {
        String data = "";
        try {
            //获取HttpClient对象
            HttpClient client = new DefaultHttpClient();
            //获取一个请求对象
            HttpPost post = new HttpPost(url);
            //把要传给服务器端的参数以name-value方式包装
            List<NameValuePair> parameters = new ArrayList<NameValuePair>();
            BasicNameValuePair param1 = new BasicNameValuePair("q", "习近平");
            BasicNameValuePair param2 = new BasicNameValuePair("key", "19f0b2ebeec053b333acaca294186851");
            parameters.add(param1);
            parameters.add(param2);
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters, "utf-8");
            //给post传参
            post.setEntity(entity);
            //往服务器改善请求
            HttpResponse response = client.execute(post);
            int statusCode = response.getStatusLine().getStatusCode();
            if(statusCode == 200){
                HttpEntity httpEntity = response.getEntity();
                data = EntityUtils.toString(httpEntity, "utf-8");
            }
            Log.i("data", data);

        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

get请求

protected void getHttpClientGet(String url) {
        String content = "";
        try {
            //获取HttpClient对象
            HttpClient client = new DefaultHttpClient();
            //构建一个请求对象
            HttpGet get = new HttpGet(url);
            //往服务器发送请求
            HttpResponse response = client.execute(get);
            //获取状态码
            int statusCode = response.getStatusLine().getStatusCode();
            if(statusCode == 200){
                //获取响应回来的实体内容
                HttpEntity entity = response.getEntity();
                content = EntityUtils.toString(entity, "utf-8");
            }
            Log.i("data", content);
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:3594次
    • 积分:173
    • 等级:
    • 排名:千里之外
    • 原创:14篇
    • 转载:0篇
    • 译文:0篇
    • 评论:1条
    文章分类
    文章存档
    最新评论