HttpClient

private static void getHttpClient(String url) {
        /* 1 构造HttpClient的实例 */
        HttpClient httpClient = new HttpClient();
        /* 2 生成 GetMethod 对象并设置参数 */
        GetMethod getMethod = new GetMethod(url);
        // 设置请求重试处理,用的是默认的重试处理:请求三次
        getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler());
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(
                5000);
        // 设置 get 请求超时为 5 秒
        getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 5000);

        /* 3 执行 HTTP GET 请求 */
        try {
            int statusCode = httpClient.executeMethod(getMethod);
            /* 4 判断访问的状态码 */
            if (statusCode != 200) {
                System.err.println("Method failed: "
                        + getMethod.getStatusLine());
            }
            /* 5 处理 HTTP 响应内容 */
            // HTTP响应头部信息,这里简单打印
            Header[] headers = getMethod.getResponseHeaders();
            for (Header h : headers)
                System.out.println(h.getName() + "~~" + h.getValue());
            // 读取 HTTP 响应内容,这里简单打印网页内容
            byte[] responseBody = getMethod.getResponseBody();// 读取为字节数组(保持原格式)
            System.out.println("byte:" + new String(responseBody));
            // // 读取为 InputStream,在网页内容数据量大时候推荐使用
            // InputStream resStream = getMethod.getResponseBodyAsStream();//
            // BufferedReader br = new BufferedReader(new InputStreamReader(
            // resStream));
            // StringBuffer resBuffer = new StringBuffer();
            // String resTemp = "";
            // while ((resTemp = br.readLine()) != null) {
            // resBuffer.append(resTemp);
            // }
            // resStream.close();
            // System.out.println("resBuffer:"+resBuffer.toString());
        } catch (HttpException e) {
            // 发生致命的异常,可能是协议不对或者返回的内容有问题
            System.out.println("Please check your provided http address!");
            e.printStackTrace();
        } catch (IOException e) {
            // 发生网络异常
            e.printStackTrace();
        } finally {
            // 释放连接
            getMethod.releaseConnection();
        }
    }

 

posted on 2013-01-07 10:15  雨渐渐  阅读(333)  评论(0编辑  收藏  举报

导航