Android使用Apache HttpClient发送GET、POST请求

本文详细介绍了如何使用Apache HttpClient进行HTTP请求,包括创建HttpClient对象、发送GET和POST请求、处理响应等内容。通过实例演示了GET和POST请求的实现方式,并提供了错误处理策略。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

简单的网页下载,HttpURLConnection可以完成,但是涉及到用户登录等权限相关问题,就需要涉及Session、Cookies。,就很难使用HttpURLConnection来处理了。Apache开源组织提供了一个HttpClient项目可以处理这些问题。HttpClient关注于如何发送请求、接受请求,以及管理HTTP链接。
使用HttpClient对象来发送请求、接受响应步骤:


创建HttpClient对象
如果要发送GET请求,创建HttpGet对象;如果是POST请求,则创建HttpPost对象。
如果需要添加参数,对于HttpGet直接在构造URL的时候填入参数。对于POST请求,使用setEntity(HttpEntity entity)方法来设置
调用HttpClient对象的execute(HttpUriRequest request)发送请求,此方法返回一个HttpResponse
调用HttpResponse的getALLHeaders()、getHeaders(String name)等方法可获取服务器响应头;调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器响应内容。
注意:


不少地方说可以使用HttpGet和HttpPost共同的setParams(HttpParams params)方法添加请求参数,但是我没有设置成功,网上搜索发现好多人也没成功。Even Apache’s official example uses URIBuilder’s setParameter method to build the params out in the URI,所以没有使用这种方法.


GET请求Demo:

public class MainActivity extends Activity {
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TextView textViewShow = (TextView) findViewById(R.id.showText);
        //直接在URL后添加请求参数
        String url = "http://192.168.1.103/index.php?get1=hello&get2=bay";
        try {
            // 创建DefaultHttpClient对象
            HttpClient httpclient = new DefaultHttpClient();
            // 创建一个HttpGet对象
            HttpGet get = new HttpGet(url);
            // 获取HttpResponse对象
            HttpResponse response = httpclient.execute(get);
            //判断是否链接成功
            if (response.getStatusLine().getStatusCode() == 200) {
                //实体转换为字符串
                String content = EntityUtils.toString(response.getEntity(),"utf-8");
                textViewShow.setText(content);
            }else{
                textViewShow.setText("网络错误");
            }
 
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
 
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
}
POST请求Demo:

public class MainActivity extends Activity {
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TextView textViewShow = (TextView) findViewById(R.id.showText);
 
        String url = "http://192.168.1.103/index.php";
        HttpClient httpClient = new DefaultHttpClient();
        try {
        HttpPost post = new HttpPost(url);
        List params = new ArrayList();
        params.add(new BasicNameValuePair("get1", "hello"));
        params.add(new BasicNameValuePair("get2", "usrl"));
 
            post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
            HttpResponse response = httpClient.execute(post);
            if(response.getStatusLine().getStatusCode() ==200){
                String content = EntityUtils.toString(response.getEntity(),"utf-8");
                textViewShow.setText(content);
 
            }else{
                textViewShow.setText("网络问题");
            }
 
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            textViewShow.setText("UnsupportedEncodingException");
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            textViewShow.setText("ClientProtocolException");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            textViewShow.setText("IOException");
        }
 
    }
 
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
 
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值