【安卓学习笔记】HTTP请求——HttpClient方式

主要知识点:

  • 不能缓存服务器响应,一般用于抓包
  • 相较于HttpUrlConnection来说,不需要关心各种输入输出流的转换
  • 步骤:获取HttpUrlConnection,获取HttpGet、HttpPost、execute获取响应(判断状态码)、对响应结果(Entity)进行转换
  • HttpPost/HttpGet.setHeader设置请求头,从response获取cookie等响应头信息

源码:

public class HttpClientRequest {

        public String getData(String path) throws Exception{
                                
                    HttpClient client = new DefaultHttpClient();
                    HttpGet httpGet = new HttpGet(path);
                    
                    HttpResponse response = client.execute(httpGet);
                    
                    if(response.getStatusLine().getStatusCode()==200){
                        HttpEntity entity = response.getEntity();
                        String data = EntityUtils.toString(entity,"utf-8");
                        return data;
                    }                   
            
            return null;
        }
        
        public String postData(String path,List<NameValuePair> parameters) throws Exception{
            
            HttpClient client = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(path);
                        
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters);
            httpPost.setEntity(entity);
            
            HttpResponse response = client.execute(httpPost);
            if(response.getStatusLine().getStatusCode()==200){
                HttpEntity responseEntity = response.getEntity();
                String data = EntityUtils.toString(responseEntity,"utf-8");
                return data;
            }
            return null;
        }
        
        
}

调用:

new Thread(){
            public void run() {             
                
                try {
                    HttpClientRequest hcr = new HttpClientRequest();
                    
                    /******************GET方式请求*********************/
                    //String str =hcr.getData("http://192.168.1.183/test.php?name=123");
                    
                    /******************POST方式请求*********************/
                    List<NameValuePair> parameters = new ArrayList<NameValuePair>();
                    parameters.add(new BasicNameValuePair("name", "xiaoming"));
                    
                    String str = hcr.postData("http://192.168.1.183/test.php",parameters);
                    
                    System.out.println(str);
                    
                } catch (Exception e) {                 
                    e.printStackTrace();
                }
                
            };
}.start();
参考自:http://www.runoob.com/w3cnote/android-tutorial-httpclient.html
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容