HttpUrlConnection实现get方法请求

java之HttpURLConnection 2020-01-06 阅读 84 评论 0

http请求的get和post,都是比较常见的方法。这篇主要是用java的HttpUrlConnection类实现get方法,在android同样适用。

get方法的实现

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Iterator;
import java.util.Map;

public class HttpGet {
    private HttpURLConnection httpConn;
    private String charset;
    // 设置连接主机服务器的超时时间:15000毫秒
    private final int CONNECT_TIMEOUT = 15000;
    // 设置读取远程返回的数据时间:60000毫秒
    private final int READ_TIMEOUT = 60000;

    /**
     * 构造方法
     *
     * @param requestURL 请求地址
     * @param charset    返回内容的编码,utf-8、gbk、gb2312等
     * @param headers    请求头
     * @throws IOException
     */
    public HttpGet(String requestURL, String charset, Map<String, String> headers) throws IOException {
        this.charset = charset;
        URL url = new URL(requestURL);
        httpConn = (HttpURLConnection) url.openConnection();
        httpConn.setConnectTimeout(CONNECT_TIMEOUT);
        httpConn.setReadTimeout(READ_TIMEOUT);
        httpConn.setRequestMethod("GET"); // 设置连接方式:get
        if (headers != null && headers.size() > 0) {
            Iterator<String> it = headers.keySet().iterator();
            while (it.hasNext()) {
                String key = it.next();
                String value = headers.get(key);
                httpConn.setRequestProperty(key, value);
            }
        }
    }

    public HttpGet(String requestURL, String charset) throws IOException {
        this(requestURL, charset, null);
    }

    /**
     * 添加请求头
     *
     * @param key
     * @param value
     */
    public void addHeader(String key, String value) {
        httpConn.setRequestProperty(key, value);
    }

    /**
     * 完成请求,并接受服务器的回应
     *
     * @return 如果请求成功,状态码是200,返回服务器返回的字符串,否则抛出异常
     * @throws IOException
     */
    public String finish() throws IOException {
        String response = "";
        // 检查服务器返回状态
        int status = httpConn.getResponseCode();
        if (status == HttpURLConnection.HTTP_OK) {
            ByteArrayOutputStream result = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int length;
            while ((length = httpConn.getInputStream().read(buffer)) != -1) {
                result.write(buffer, 0, length);
            }
            response = result.toString(this.charset);
            httpConn.disconnect();
        } else {
            throw new IOException("Server returned non-OK status: " + status);
        }
        return response;
    }
}

调用示例

比如需要查询指定ip地址的相关信息,爬虫 http://www.ip138.com 网站,传递指定ip地址,此接口返回的内容编码是gbk,实例化HttpUrlConnectionGet时,指定返回内容为gbk编码,避免出现乱码。

try {
    // 请求头
    Map<String, String> headers = new HashMap<>();
    headers.put("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36");
    HttpGet httpGet = new HttpGet("http://www.ip138.com/iplookup.asp?ip=8.8.8.8&action=2", "gbk", headers);
    // 返回信息
    String response = httpGet.finish();
    System.out.println(response);
} catch (Exception e) {
    e.printStackTrace();
}

在设置请求参数中,会碰到含有特殊符号或者中文字符的情况,最好是确保参数的键和值都用 URLEncoder.encode(String s, String enc) 方法,指定一个编码,如utf-8或者gbk等。

try {
    StringBuilder sb = new StringBuilder();
    sb.append(URLEncoder.encode("test", "UTF-8"));
    sb.append("=");
    sb.append(URLEncoder.encode("测试", "UTF-8"));
    HttpGet multipart = new HttpGet("http://localhost?" + sb.toString(), "utf-8");
    // 返回信息
    String response = multipart.finish();
    System.out.println(response);
} catch (Exception e) {
    e.printStackTrace();
}
最后更新 2020-02-26