• JAVA_GET请求URL


      1 import java.io.IOException;
      2 
      3 import net.sf.json.JSONObject;
      4 
      5 import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
      6 import org.apache.commons.httpclient.Header;
      7 import org.apache.commons.httpclient.HttpClient;
      8 import org.apache.commons.httpclient.HttpException;
      9 import org.apache.commons.httpclient.HttpStatus;
     10 import org.apache.commons.httpclient.methods.GetMethod;
     11 import org.apache.commons.httpclient.params.HttpMethodParams;
     12 import org.apache.http.HttpEntity;
     13 import org.apache.http.HttpResponse;
     14 import org.apache.http.client.methods.HttpPost;
     15 import org.apache.http.entity.StringEntity;
     16 import org.apache.http.impl.client.DefaultHttpClient;
     17 import org.apache.http.util.EntityUtils;
     18 
     19 public class TestGetRequest {
     20 
     21     /**
     22      * @param args
     23      */
     24     public static void main(String[] args) {
     25 
     26         String url = "http://www.ecmwf.int/plots/get-map/";
     27         String param = "{"product":{"product":{"name":"public_plots","package":"medium"},"values":{"time":["2016032012",48,"2016032212"],"parameter":"Wind 850 and mslp","area":"Asia"}}}";
     28         System.out.println(param);
     29         JSONObject object = JSONObject.fromObject(param);
     30         JSONObject result = doPost(url, object);
     31         System.out.println(result);
     32         JSONObject imgResult = (JSONObject) result.get("result");
     33         System.out.println(imgResult.get("url"));
     34     }
     35 
     36     public static String doGet(String url, String charset) throws Exception {
     37         /*
     38          * 使用 GetMethod 来访问一个 URL 对应的网页,实现步骤: 1:生成一个 HttpClinet 对象并设置相应的参数。
     39          * 2:生成一个 GetMethod 对象并设置响应的参数。 3:用 HttpClinet 生成的对象来执行 GetMethod 生成的Get
     40          * 方法。 4:处理响应状态码。 5:若响应正常,处理 HTTP 响应内容。 6:释放连接。
     41          */
     42         /* 1 生成 HttpClinet 对象并设置参数 */
     43         HttpClient httpClient = new HttpClient();
     44         // 设置 Http 连接超时为5秒
     45         httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(
     46                 5000);
     47         /* 2 生成 GetMethod 对象并设置参数 */
     48         GetMethod getMethod = new GetMethod(url);
     49         // 设置 get 请求超时为 5 秒
     50         getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 5000);
     51         // 设置请求重试处理,用的是默认的重试处理:请求三次
     52         getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
     53                 new DefaultHttpMethodRetryHandler());
     54         String response = "";
     55         /* 3 执行 HTTP GET 请求 */
     56         try {
     57             int statusCode = httpClient.executeMethod(getMethod);
     58             /* 4 判断访问的状态码 */
     59             if (statusCode != HttpStatus.SC_OK) {
     60                 System.err.println("请求出错: " + getMethod.getStatusLine());
     61             }
     62             /* 5 处理 HTTP 响应内容 */
     63             // HTTP响应头部信息,这里简单打印
     64             Header[] headers = getMethod.getResponseHeaders();
     65             for (Header h : headers)
     66                 System.out
     67                         .println(h.getName() + "------------ " + h.getValue());
     68             // 读取 HTTP 响应内容,这里简单打印网页内容
     69             byte[] responseBody = getMethod.getResponseBody();// 读取为字节数组
     70             response = new String(responseBody, charset);
     71             System.out.println("----------response:" + response);
     72             // 读取为 InputStream,在网页内容数据量大时候推荐使用
     73             // InputStream response = getMethod.getResponseBodyAsStream();
     74         } catch (HttpException e) {
     75             // 发生致命的异常,可能是协议不对或者返回的内容有问题
     76             System.out.println("请检查输入的URL!");
     77             e.printStackTrace();
     78         } catch (IOException e) {
     79             // 发生网络异常
     80             System.out.println("发生网络异常!");
     81             e.printStackTrace();
     82         } finally {
     83             /* 6 .释放连接 */
     84             getMethod.releaseConnection();
     85         }
     86         return response;
     87     }
     88 
     89     public static JSONObject doPost(String url, JSONObject json) {
     90         DefaultHttpClient client = new DefaultHttpClient();
     91         HttpPost post = new HttpPost(url);
     92         JSONObject response = null;
     93         try {
     94             StringEntity s = new StringEntity(json.toString());
     95             s.setContentEncoding("UTF-8");
     96             s.setContentType("application/json");// 发送json数据需要设置contentType
     97             post.setEntity(s);
     98             HttpResponse res = client.execute(post);
     99             if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
    100                 HttpEntity entity = res.getEntity();
    101                 String result = EntityUtils.toString(res.getEntity());// 返回json格式:
    102                 response = JSONObject.fromObject(result);
    103             }
    104         } catch (Exception e) {
    105             throw new RuntimeException(e);
    106         }
    107         return response;
    108     }
    109 
    110 }
  • 相关阅读:
    Java接口(interface),扫盲贴
    Java抽象类,扫盲贴
    Java类的继承、super关键字、复写
    Java内部类,扫盲贴
    数据结构学习笔记1--简单排序
    7.1 通用的职责分配软件原则 GRASP原则一: 创建者 Creator
    6.6 面向对象设计
    6.5 开始进入设计 … Transition to Design
    6.4 操作契约 Operation Contracts
    6.3 契约式设计
  • 原文地址:https://www.cnblogs.com/bilaisheng/p/5464131.html
Copyright © 2020-2023  润新知