乐趣区

封装HttpUrlConnection开箱即用

【本文版权归微信公众号 ” 代码艺术 ”(ID:onblog)所有,若是转载请务必保留本段原创声明,违者必究。若是文章有不足之处,欢迎关注微信公众号私信与我进行交流!】

因为经常用到 便写出来方边使用 直接复制本类即可

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
/**
 * 封装 HttpURLConnection 开箱即用
 * Create by yster@foxmail.com 2018/9/10/010 19:17
*/public class HttpUtil {
private HttpURLConnection connection;
private Charset charset = Charset.forName("UTF-8");
private int readTimeout = 32000;
private int connectTimeout = 10000;
private String method = "GET";
private boolean doInput = true;
private Map<String, String> headers = null;
private String data = null;
/**
     * 实例化对象
*/
    public static HttpUtil connect(String url) throws IOException {return new HttpUtil((HttpURLConnection) new URL(url).openConnection());
    }
/**
     * 禁止 new 实例
*/
    private HttpUtil() {}
private HttpUtil(HttpURLConnection connection) {this.connection = connection;}
/**
     * 设置读去超时时间 /ms
     *
     * @param timeout
*/
    public HttpUtil setReadTimeout(int timeout) {
this.readTimeout = timeout;
return this;
    }
/**
     * 设置链接超时时间 /ms
     *
     * @param timeout
*/
    public HttpUtil setConnectTimeout(int timeout) {
this.connectTimeout = timeout;
return this;
    }
/**
     * 设置请求方式
     *
     * @param method
*/
    public HttpUtil setMethod(String method) {
this.method = method;
return this;
    }
/**
     * 添加 Headers
     *
     * @param map
*/
    public HttpUtil setHeaders(Map<String, String> map) {
        String cookie = "Cookie";
if (map.containsKey(cookie)) {headers = new HashMap<>();
            headers.put(cookie, map.get(cookie));
        }
return this;
    }
/**
     * 是否接受输入流
     * 默认 true
     *
     * @param is
*/
    public HttpUtil setDoInput(boolean is) {
this.doInput = is;
return this;
    }
/**
     * 设置请求响应的编码
*/
    public HttpUtil setCharset(String charset) {this.charset = Charset.forName(charset);
return this;
    }
/**
     * 写入数据, 接受 Map&lt;String,String&gt; 或 String 类型 &lt;br&gt;
     * 例如 POST 时的参数 &lt;br&gt;
     * demo=1&amp;name=2
*/
    public HttpUtil setData(Object object) {if (object == null) {return this;} else if (object instanceof String) {this.data = (String) object;
        } else if (object instanceof Map) {Map map = (Map) object;
            StringBuilder builder = new StringBuilder();
for (Object key : map.keySet()) {builder.append(key + "=" + map.get(key) + "&");
            }
this.data = builder.toString().substring(0, builder.length() > 0 ? builder.length() - 1 : builder.length());
        }
return this;
    }
/**
     * 发起请求
*/
    public HttpUtil execute() throws IOException {
// 添加请求头
        if (headers != null) {for (String key : headers.keySet()) {connection.setRequestProperty(key, headers.get(key));
            }
        }
// 设置读去超时时间为 10 秒        connection.setReadTimeout(readTimeout);
// 设置链接超时为 10 秒        connection.setConnectTimeout(connectTimeout);
// 设置请求方式,GET,POST        connection.setRequestMethod(method.toUpperCase());
// 接受输入流        connection.setDoInput(doInput);
// 写入参数
        if (data != null && !method.equalsIgnoreCase("GET")) {
// 启动输出流,当需要传递参数时需要开启
            connection.setDoOutput(true);
// 添加请求参数,注意:如果是 GET 请求,参数要写在 URL 中
            OutputStream output = connection.getOutputStream();
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(output, charset));
// 写入参数 用 &amp; 分割。writer.write(data);
            writer.flush();
            writer.close();}
// 发起请求        connection.connect();
return this;
    }
/**
     * 获取 HttpURLConnection
*/
    public HttpURLConnection getConnection() {return this.connection;}
/**
     * 获取响应字符串
*/
    public String getBody(String... charsets) {
// 设置编码
        String charset = "UTF-8";
if (charsets.length > 0) {charset = charsets[0];
        }
// 读取输入流
        try {InputStream inputStream = connection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, charset));
            String line = bufferedReader.readLine();
            StringBuilder builder = new StringBuilder();
while (line != null) {builder.append(line);
                line = bufferedReader.readLine();}
return builder.toString();} catch (IOException e) {e.printStackTrace();
        }
// 失败返回 NULL
        return null;
    }
public static void main(String[] args) throws IOException {String body = HttpUtil.connect("http://www.baidu.com")
                .setMethod("GET")
                .setCharset("UTF-8")
                .execute()
                .getBody();
        System.out.println(body);
    }

}

版权声明

【本文版权归微信公众号 ” 代码艺术 ”(ID:onblog)所有,若是转载请务必保留本段原创声明,违者必究。若是文章有不足之处,欢迎关注微信公众号私信与我进行交流!】

退出移动版