这里只以 GET 请求为例,对比分别使用 JDK 和 Commons HttpClient 实现的代码。
采用 JDK API 的方式:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| InputStream in = null; try { URLConnection connection = new URL(url).openConnection(); connection.setConnectTimeout(1000 * 3); connection.setReadTimeout(1000 * 3); connection.connect(); in = connection.getInputStream(); int byteRead; byte[] buffer = new byte[1024 * 4]; StringBuilder stringBuilder = new StringBuilder(); while ((byteRead = in.read(buffer)) != -1) { stringBuilder.append(new String(buffer, 0, byteRead)); } String response = stringBuilder.toString(); } catch (IOException e) { } finally { FileUtils.close(in); }
|
采用 Commons HttpClient 类库的方式:
1 2 3 4 5 6 7 8 9 10 11 12
| HttpClient client = new HttpClient(); client.getHttpConnectionManager().getParams().setConnectionTimeout(1000 * 3); client.getHttpConnectionManager().getParams().setSoTimeout(1000 * 3); HttpMethod method = new GetMethod(url); method.setQueryString("id=1"); client.executeMethod(method); String response = method.getResponseBodyAsString(); method.releaseConnection();
|