• Android--网络请求


    1、Android 上发送HTTP 请求的方式一般有两种,HttpURLConnection 和 HttpClient;

    2、HttpURLConnection 的用法:

      1)获取 HttpURLConnection 实例:通过调用 URL 对象的 openConnection() 方法获取;

      2)设置 HTTP 请求所使用的方法,常用的有两个方法: GET 和 POST;

      3)其他设置,比如设置连接超时、读取超时的毫秒数等;

    connection.setConnectTimeout(8000);
    connection.setReadTimeout(8000);

      4)调用 HttpURLConnection 的 getInputStream() 方法可以获取到服务器返回的输入流,通过这个输入流就可以读取到服务端数据;

      5)最后需要调用 disconnect() 方法来关闭连接。

      6)示例代码:

    private String sendRequestWithHttpURLConnection(){
        String result = null;
        HttpURLConnection connection = null;
        try{
            URL url = new URL("http://www.baidu.com");
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(8000);
            connection.setReadTimeout(8000);
            InputStream inputStream = connection.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
            StringBuilder sb = new StringBuilder();
            String str;
            while((str = br.readLine()) != null){
                sb.append(str);
            }
            result = sb.toString();
        }catch (Exception e){
            e.printStackTrace();
        }finally{
            if(connection != null){
                connection.disconnect();
            }
        }
        return result;
    }

    3、HttpClient 的用法:

      1)HttpClient 是一个接口,通常情况下会创建一个 DefaultHttpClient 的实例:HttpClient httpClient = new DefaultHttpClient();

      2)设置请求:

        --GET 请求:创建一个 HttpGet 对象,并传入目标的网络地址,然后调用 HttpClient 的 execute() 方法即可;

        --POST请求:创建一个 HttpPost 对象,并传入目标的网络地址;创建一个 NameValuePair 集合来存放待提交的参数,并将这个参数集合传入到一个UrlEncodedFormEntity 中,然后调用 HttpPost 的 setEntity() 方法将构建好的 UrlEncodedFormEntity传入:

    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("username", "admin"));
    params.add(new BasicNameValuePair("password", "123456"));
    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, "utf-8");
    httpPost.setEntity(entity);

      3)调用 HttpClient 的 execute() 方法发起请求;

      4)执行 execute() 方法之后会返回一个 HttpResponse,对象服务器所返回的所有信息就会包含在这里面,通常情况先取出服务器返回的状态码,如果等于200 就说明请求和响应都成功了,此时可以调用 getEntity() 方法获取到一个HttpEntity 实例,然后再用 EntityUtils.toString() 这个静态方法将 HttpEntity 转换成字符串;

      5)示例代码:

    private String sendRequestWithHttpClient(String name, String pwd){
        String result = null;
        HttpClient httpClient = null;
        try {
            httpClient = new DefaultHttpClient();
            HttpPost post = new HttpPost("http://www.baidu.com");
    
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("name", name));
            params.add(new BasicNameValuePair("pwd", pwd));
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
            post.setEntity(entity);
    
            HttpResponse response = httpClient.execute(post);
            if(response.getStatusLine().getStatusCode() == 200){
                HttpEntity entity1 = response.getEntity();
                result = EntityUtils.toString(entity1, "UTF-8");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }
  • 相关阅读:
    ZeroMQ自查手册
    如何回答——请简述MySQL索引类型
    101. 对称二叉树
    66. 加一
    104. 二叉树的最大深度
    724.寻找数组的中心索引
    33. 搜索旋转排序数组
    快速排序
    Vue
    HTML
  • 原文地址:https://www.cnblogs.com/tengtao93/p/5287689.html
Copyright © 2020-2023  润新知