前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >总结几个最近处理问题中使用个几个代码demo

总结几个最近处理问题中使用个几个代码demo

作者头像
小勇DW3
发布2019-12-10 17:47:31
4260
发布2019-12-10 17:47:31
举报
文章被收录于专栏:小勇DW3小勇DW3小勇DW3

demo1:几个不同的http请求方式总结:

-------------------------------------------------------------------------------------------------

Post新版本的请求方式:

 基于的版本:

<!--&lt;!&ndash; https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient &ndash;&gt;-->
<!--<dependency>-->
    <!--<groupId>org.apache.httpcomponents</groupId>-->
    <!--<artifactId>httpclient</artifactId>-->
    <!--<version>4.5.5</version>-->
<!--</dependency>-->
// String uploadResponse = Request.Post(nodeAddress + "/" + bucketName + "/" + objectName)
//        .addHeader("x-nos-token", uploadToken)
//        .bodyByteArray(chunkData, 0, readLen)
//        .execute()
//        .returnContent()
//        .toString();

-------------------------------------------------------------------------------------------------

Post请求版本方式二:

//    public static String doPost(String url, String token, byte[] chunk, int off, int len)
//    {
//        CloseableHttpClient httpClient = null;
//        CloseableHttpResponse httpResponse = null;
//        String result = "";
//        // 创建httpClient实例
//        httpClient = HttpClients.createDefault();
//        // 创建httpPost远程连接实例
//        HttpPost httpPost = new HttpPost(url);
//        // 配置请求参数实例
//        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000)// 设置连接主机服务超时时间
//                .setConnectionRequestTimeout(35000)// 设置连接请求超时时间
//                .setSocketTimeout(60000)// 设置读取数据连接超时时间
//                .build();
//        // 为httpPost实例设置配置
//        httpPost.setConfig(requestConfig);
//        // 设置请求头
//        httpPost.addHeader("x-nos-token", token);
//        // 封装post请求参数
//        // 为httpPost设置封装好的请求参数
//        HttpEntity requestEntity = new ByteArrayEntity(chunk, 0, len);
//        httpPost.setEntity(requestEntity);
//
//        try {
//            // httpClient对象执行post请求,并返回响应参数对象
//            httpResponse = httpClient.execute(httpPost);
//            // 从响应对象中获取响应内容
//            HttpEntity entity = httpResponse.getEntity();
//            result = EntityUtils.toString(entity);
//        } catch (ClientProtocolException e) {
//            e.printStackTrace();
//        } catch (IOException e) {
//            e.printStackTrace();
//        } finally {
//            // 关闭资源
//            if (null != httpResponse) {
//                try {
//                    httpResponse.close();
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }
//            if (null != httpClient) {
//                try {
//                    httpClient.close();
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }
//        }
//        return result;
//    }

-------------------------------------------------------------------------------------------------

Post请求版本方式二:

public static String sendPost(String url, String token, byte[] chunk, int off, int len)
{
    // 创建httpClient实例对象
    HttpClient httpClient = new HttpClient();
    // 设置httpClient连接主机服务器超时时间:15000毫秒
    httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(15000);
    // 创建post请求方法实例对象
    PostMethod postMethod = new PostMethod(url);
    // 设置post请求超时时间
    postMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 60000);
    postMethod.addRequestHeader("x-nos-token", token);
    try {
        //json格式的参数解析

        RequestEntity entity = new ByteArrayRequestEntity(chunk);
        postMethod.setRequestEntity(entity);

        httpClient.executeMethod(postMethod);
        String result = postMethod.getResponseBodyAsString();
        postMethod.releaseConnection();
        return result;
    } catch (IOException e) {
        logger.info("POST请求发出失败!!!");
        e.printStackTrace();
    }
    return null;
}

-------------------------------------------------------------------------------------------------

-------------------------------------------------------------------------------------------------

GET请求方式一:

public static String doGet(String httpurl)
{
    HttpURLConnection connection = null;
    InputStream is = null;
    BufferedReader br = null;
    // 返回结果字符串
    String result = null;

    try {
        // 创建远程url连接对象
        URL url = new URL(httpurl);
        // 通过远程url连接对象打开一个连接,强转成httpURLConnection类
        connection = (HttpURLConnection) url.openConnection();
        // 设置连接方式:get
        connection.setRequestMethod("GET");
        // 设置连接主机服务器的超时时间:15000毫秒
        connection.setConnectTimeout(15000);
        // 设置读取远程返回的数据时间:60000毫秒
        connection.setReadTimeout(60000);
        // 发送请求
        connection.connect();
        // 通过connection连接,获取输入流
        if (connection.getResponseCode() == 200) {
            is = connection.getInputStream();
            // 封装输入流is,并指定字符集
            br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            // 存放数据
            StringBuffer sbf = new StringBuffer();
            String temp = null;
            while ((temp = br.readLine()) != null) {
                sbf.append(temp);
                sbf.append("\r\n");
            }
            result = sbf.toString();
        }
    } catch (MalformedURLException e) {
        logger.error("非法地址格式异常...");
        e.printStackTrace();
    } catch (IOException e) {
        logger.error("Get请求中IO流出现异常");
        e.printStackTrace();
    } finally {
        // 关闭资源
        if (null != br) {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        if (null != is) {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        connection.disconnect();// 关闭远程连接
    }

    return result;
}

-------------------------------------------------------------------------------------------------

过程问题记录:

在使用get请求的时候,如果URL中的请求参数包含了特殊字符,需要对特殊字符进行转义:

有些字符在URL中具有特殊含义,基本编码规则如下:
特殊含义                                             十六进制值 
1.+ 表示空格(在 URL 中不能使用空格)                    %20 
2./ 分隔目录和子目录                                   %2F 
3.? 分隔实际的 URL 和参数                              %3F 
4.% 指定特殊字符                                      %25 
5.# 表示书签                                         %23 
6.& URL 中指定的参数间的分隔符                         %26 

解决方法:

//对鉴权参数做AES加密处理
requestId = java.net.URLEncoder.encode( AESCryptUtils.encode(requestId) );
data = java.net.URLEncoder.encode( AESCryptUtils.encode(data) );
action = java.net.URLEncoder.encode( AESCryptUtils.encode(action) );
String URL = AUTH_URL + "?" + "data=" + data + "&requestId=" + requestId + "&action=" + action;
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-12-04 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档