作者:pxrty_635 | 来源:互联网 | 2023-02-03 20:01
网上利用java发送http请求的代码很多,一搜一大把,有的利用的是java.net.*下的HttpURLConnection,有的用httpclient,而且发送的代码也分门别类。今天我们主要
网上利用java发送http请求的代码很多,一搜一大把,有的利用的是java.net.*下的HttpURLConnection,有的用httpclient,而且发送的代码也分门别类。今天我们主要来说的是利用httpclient发送请求。
httpclient又可分为
- httpclient3.x
- httpclient4.x到httpclient4.3以下
- httpclient4.3以上
不同httpclient版本其请求发送的方式也不一样,下面来做个归纳
httpclient3.x
- HttpClient client = new HttpClient();
-
-
-
- HttpMethodmethod = new GetMethod("http://java.sun.com");
-
-
- client.executeMethod(method);
-
- System.out.println(method.getStatusLine());
-
- System.out.println(method.getResponseBodyAsString());
-
- method.releaseConnection();
httpclient4.x到httpclient4.3以下
- public void getUrl(String url, String encoding) throws ClientProtocolException, IOException {
- HttpClient client = new DefaultHttpClient();
- HttpGet get = new HttpGet(url);
-
- HttpParams params = client.getParams();
- HttpConnectionParams.setConnectionTimeout(params, (int) 10 * 1000);
- HttpConnectionParams.setSoTimeout(params, 10 * 1000);
- HttpResponse response = client.execute(get);
- HttpEntity entity = response.getEntity();
- if (entity != null) {
- InputStream instream = entity.getContent();
- try {
- BufferedReader reader = new BufferedReader(new InputStreamReader(instream, encoding));
- System.out.println(reader.readLine());
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- instream.close();
- }
- }
-
- client.getConnectionManager().shutdown();
- }
httpclient4.3以上
- import org.apache.http.HttpEntity;
- import org.apache.http.HttpResponse;
- import org.apache.http.client.methods.HttpGet;
- import org.apache.http.impl.client.CloseableHttpClient;
- import org.apache.http.impl.client.HttpClients;
- import org.apache.http.util.EntityUtils;
-
-
- public static String getResult(String urlStr) {
- CloseableHttpClient httpClient = HttpClients.createDefault();
-
- HttpGet httpGet = new HttpGet(urlStr);
-
-
-
-
- String res = "";
- try {
-
- HttpResponse getAddrResp = httpClient.execute(httpGet);
- HttpEntity entity = getAddrResp.getEntity();
- if (entity != null) {
- res = EntityUtils.toString(entity);
- }
- log.info("响应" + getAddrResp.getStatusLine());
- } catch (Exception e) {
- log.error(e.getMessage(), e);
- return res;
- } finally {
- try {
- httpClient.close();
- } catch (IOException e) {
- log.error(e.getMessage(), e);
- return res;
- }
- }
- return res;
- }