博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
http请求工具类
阅读量:7095 次
发布时间:2019-06-28

本文共 3371 字,大约阅读时间需要 11 分钟。

hot3.png

public class HttpRequestUtils {

    private static final int connectTimeout = 1000 * 60;/* 连接超时时间 */
    private static final int socketTimeout = 1000 * 180;/* 读取数据超时时间 */
     /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url
     *            发送请求的 URL
     * @param param
     *            请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
public static String sendPost(String urlStr, String content) {
    URL url = null;
    HttpURLConnection connection = null;
    try {
        url = new URL(urlStr);
        connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setRequestMethod("POST");
        connection.setUseCaches(false);
        connection.setRequestProperty("Accept", "application/json"); // 设置接收数据的格式 
        connection.setRequestProperty("Content-Type", "application/json"); // 设置发送数据的格式 
        connection.connect();
        OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); // utf-8编码 
        out.append(content); 
        out.flush(); 
        out.close();

        BufferedReader reader = new BufferedReader(new InputStreamReader(

                connection.getInputStream(), "utf-8"));

        StringBuffer buffer = new StringBuffer();

        String line = "";
        while ((line = reader.readLine()) != null) {
            buffer.append(line);
        }
        reader.close();
        String result = buffer.toString();
        return result;
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
    return null;
}

/** HttpClientPost */

public static String doPost(String url, List<BasicNameValuePair> params, StringBuilder sb) {
    /* 创建HttpClinet实例 */
    CloseableHttpClient client = HttpClients.createDefault();
    /* 设置请求和传输超时时间 */
    RequestConfig config = RequestConfig.custom().setConnectTimeout(connectTimeout).setSocketTimeout(socketTimeout).build();
    sb.append("地址:" + url);
    System.out.println("地址:" + url);
    /* 创建Post方法实例 */
    HttpPost post = new HttpPost(url);
    post.setConfig(config);
    HttpEntity entity;
    StringBuffer result = new StringBuffer();
    long startTime = 0, endTime = 0;
    try {
        if (params != null) {/* 设置参数 */
            entity = new UrlEncodedFormEntity(params, "UTF-8");
            post.setEntity(entity);
            System.out.println("参数:" + EntityUtils.toString(entity));
        }
        startTime = System.nanoTime();
        CloseableHttpResponse response = client.execute(post);
        int code = response.getStatusLine().getStatusCode();
        System.out.println("状态码:" + code);
        if (code == 200 || code == 500) {
            try {
                entity = response.getEntity();
                if (entity != null) {
                    long len = entity.getContentLength();
                    if (len != -1 && len < 2048) {/* 当返回值长度较小的时候,使用工具类 */
                        result.append(EntityUtils.toString(entity));
                    } else {/* 否则使用IO流来读取 */
                        BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"));
                        String line;
                        while ((line = reader.readLine()) != null) {
                            result.append(line);
                        }
                        reader.close();
                    }
                    endTime = System.nanoTime();
                    sb.append("返回:" + result.toString());
                    System.out.println("返回:" + result.toString());
                }
            } catch (Exception e) {
                endTime = System.nanoTime();
                sb.append("通讯错误:" + e.getMessage());
            } finally {
                response.close();
            }
        } else {
            endTime = System.nanoTime();
            post.abort();
            sb.append("错误请求!状态码:" + code);
        }
    } catch (IOException e) {
        endTime = System.nanoTime();
        sb.append("通讯时发生异常:" + e.getMessage());
    } finally {
        try {
            client.close();
        } catch (IOException e) {
        }
    }
    System.out.println("用时:" + (endTime - startTime) / 1000000L + "毫秒");
    return result.toString();
}
}

转载于:https://my.oschina.net/liujiawan/blog/483382

你可能感兴趣的文章
nginx 配置白名单
查看>>
iOS开发助手、ipa上传工具、苹果APP快速上架辅助工具Appuploader
查看>>
Rstudio编辑界面美化设置
查看>>
重写对象ToString方法
查看>>
备忘: C++中的 vector 容器
查看>>
smt中查看图片与视频缩略图中,如何获得小视频的长度。
查看>>
图片(img标签)的onerror事件
查看>>
2013应届毕业生“百度”校招应聘总结
查看>>
CentOS系统启动流程
查看>>
SQLite数据库_实现简单的增删改查
查看>>
批量查询 xml的方式 还一种是表变量
查看>>
Java7/8 中 HashMap 和 ConcurrentHashMap的对比和分析
查看>>
Java 实现多线程切换等待唤醒交替打印奇偶数
查看>>
1077. Kuchiguse (20)
查看>>
HotSpot模板解释器目标代码生成过程源码分析
查看>>
c99标准 数据类型
查看>>
一维最大子数组和(续)
查看>>
Hillstone基础上网配置
查看>>
几种session存储方式比较
查看>>
习惯的颠覆
查看>>