通常情况下,我们都使用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(); } } }