网络编程(二)HttpURLConnection

学习自Android进阶之光

接着上一篇之后,我们开始学习Android基础网络编程的工具之二

HttpURLConnection

学习这个,我们按照原来的步骤来:

首先,去实现Get请求:

同样的,我们先去编写一个配置参数的得到HttpURLConnection对象的方法

/**
 *
 * @param url
 * @return HttpURLConnection
 * @description
 * * 用于得到配置参数后的HttpURLConnection实例对象(GET)
 * 1、通过url得到一个HttpURLConnection对象
 * 2、设置参数
 * 3、返回HttpURLConnection对象实例
 */
public static HttpURLConnection getConnectionForGet(@NonNull String url){
    HttpURLConnection urlConnection = null;
    try{
        URL murl = new URL(url);
        urlConnection = (HttpURLConnection) murl.openConnection();
        //设置连接超时
        urlConnection.setConnectTimeout(5000);
        //设置读取超时时间
        urlConnection.setReadTimeout(5000);
        //设置请求参数
        urlConnection.setRequestMethod("GET");
        //设置Header
        urlConnection.setRequestProperty("Connection","Keep-Alive");
        //开启接收流
        urlConnection.setDoInput(true);
        //开启传参
        urlConnection.setDoOutput(true);
    }catch (IOException e){
        e.printStackTrace();
    }
    return urlConnection;
}


然后,编写发送请求的代码

/**
 *
 * @param url
 * @description
 * 用于发送HttpURLConnection中的Get请求
 * 1、得到HttpURLConnection实例对象
 * 2、发送请求得到响应参数
 * 4、处理结果
 */
private void useHttpUrlConnectionGet(@NonNull String url){
    InputStream inputStream = null;
    HttpURLConnection urlConnection = GetHttpURLConnection.getConnectionForGet(url);
    try{
        urlConnection.connect();
        inputStream = urlConnection.getInputStream();
        final int code = urlConnection.getResponseCode();
        final String respose = ToString.converStreamToString(inputStream);
        Log.d("HttpClient","请求状态码:"+code+"\n请求结果:\n"+respose);
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                hello.setText("请求状态码:"+code+"\n请求结果:\n"+respose);
            }
        });
        inputStream.close();
    }catch (IOException e){
        e.printStackTrace();
    }
}

最后,在主线程中开子线程发送请求

 new Thread(new Runnable() {
            @Override
            public void run() {
//                useHttpClientGet("http://baidu.com");
//                useHttpClientPost("https://www.apiopen.top/femaleNameApi");
//                useHttpUrlConnectionPost("https://www.apiopen.top/femaleNameApi");
                useHttpUrlConnectionGet("http://baidu.com");
            }
        }).start();

结果为:

 

其实,HttpURLConnectionPOST请求和GET请求的代码差不多,只是设置的请求方式不同而已。如:

POST请求

第一步代码如下:


/**
 *
 * @param url
 * @return HttpURLConnection
 * @description
 * * 用于得到配置参数后的HttpURLConnection实例对象(POST)
 * 1、通过url得到一个HttpURLConnection对象
 * 2、设置参数
 * 3、返回HttpURLConnection对象实例
 */
public static HttpURLConnection getConnection(@NonNull String url){
    HttpURLConnection urlConnection = null;
    try{
        URL murl = new URL(url);
        urlConnection = (HttpURLConnection) murl.openConnection();
        //设置连接超时
        urlConnection.setConnectTimeout(5000);
        //设置读取超时时间
        urlConnection.setReadTimeout(5000);
        //设置请求参数
        urlConnection.setRequestMethod("POST");
        //设置Header
        urlConnection.setRequestProperty("Connection","Keep-Alive");
        //开启接收流
        urlConnection.setDoInput(true);
        //开启传参
        urlConnection.setDoOutput(true);
    }catch (IOException e){
        e.printStackTrace();
    }
    return urlConnection;
}

第二步代码如下:

/**
 *
 * @param url
 * @description
 * 用于发送HttpURLConnection中的Post请求
 * 1、得到HttpURLConnection实例对象
 * 2、加入参数到HttpURLConnection对象的输出流里面
 * 3、发送请求得到响应参数
 * 4、处理结果
 */
private void useHttpUrlConnectionPost(@NonNull String url){
    InputStream inputStream = null;
    HttpURLConnection urlConnection = GetHttpURLConnection.getConnection(url);
    try{

        List<NameValuePair> pairs = new ArrayList<>();
        pairs.add(new BasicNameValuePair("page","1"));
        GetHttpURLConnection.postParams(urlConnection.getOutputStream(),pairs);
        urlConnection.connect();
        inputStream = urlConnection.getInputStream();
        final int code = urlConnection.getResponseCode();
        final String respose = ToString.converStreamToString(inputStream);
        Log.d("HttpClient","请求状态码:"+code+"\n请求结果:\n"+respose);
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                hello.setText("请求状态码:"+code+"\n请求结果:\n"+respose);
            }
        });
        inputStream.close();
    }catch (IOException e){
        e.printStackTrace();
    }
}

这里,我们涉及到了传入参数的过程,我们编写一个传参的方法:

public static void postParams(OutputStream output , List<NameValuePair> pairs) throws IOException {
    StringBuffer buffer = new StringBuffer();
    for(NameValuePair pair:pairs){
        if(!TextUtils.isEmpty(buffer)){
            buffer.append("&");
        }
        buffer.append(URLEncoder.encode(pair.getName(), "UTF-8"));
        buffer.append("=");
        buffer.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
    }
    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(output,"UTF-8"));
    writer.write(buffer.toString());
    writer.flush();
    writer.close();
}

最后,我们在子线程中发送请求

new Thread(new Runnable() {
            @Override
            public void run() {
//                useHttpClientGet("http://baidu.com");
//                useHttpClientPost("https://www.apiopen.top/femaleNameApi");
                useHttpUrlConnectionPost("https://www.apiopen.top/femaleNameApi");
//                useHttpUrlConnectionGet("http://baidu.com");
            }
        }).start();

结果为:


猜你喜欢

转载自blog.csdn.net/full_stack_developer/article/details/79869799
今日推荐