X

使用Java原生HttpURLConnection快速的完成一个http请求

通常情况下,我们都使用Apache的HttpClient来发起一个http请求,我们再提供一个思路, 使用Java原生的HttpURLConnection发起一个http请求,示例代码如下:

public HttpResult GetContent(String url) throws IOException {
        HttpURLConnection conn = null;
        try {
            conn = (HttpURLConnection) new URL(url).openConnection();
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(5000);
            conn.setRequestMethod("GET");
            conn.connect(); 
            int respCode = conn.getResponseCode(); 
            String resp = null;
            if (200 == respCode) {
                resp = IOUtils.toString(conn.getInputStream(), null);
            } else {
                resp = IOUtils.toString(conn.getErrorStream(), null);
            }
            return new HttpResult(respCode, resp);
        } finally {
            if (conn != null) {
                conn.disconnect();
            }
        }
    }

 

Categories: Java学习
龙安_任天兵: 不忘初心,方得始终!