zoukankan      html  css  js  c++  java
  • 总结几个最近处理问题中使用http协议的代码

     正文前先来一波福利推荐:

    福利一:

    百万年薪架构师视频,该视频可以学到很多东西,是本人花钱买的VIP课程,学习消化了一年,为了支持一下女朋友公众号也方便大家学习,共享给大家。

    福利二:

    毕业答辩以及工作上各种答辩,平时积累了不少精品PPT,现在共享给大家,大大小小加起来有几千套,总有适合你的一款,很多是网上是下载不到。

    获取方式:

    微信关注 精品3分钟 ,id为 jingpin3mins,关注后回复   百万年薪架构师 ,精品收藏PPT  获取云盘链接,谢谢大家支持!

     

    ------------------------正文开始---------------------------

    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("
    ");
                }
                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;
    

      

  • 相关阅读:
    ibatis命名空间namespace的使用
    MyEclipse 下新建Flex与JAVA交互项目
    第2章 TCP/IP 和Internet
    第一部分:TCP/IP 基础 第一章 开放式通信模型简介
    01-布局扩展-利用盒模型完成圣杯布局(双飞翼布局)
    01-布局扩展-用calc来计算实现双飞翼布局
    01-布局扩展-BFC完成圣杯布局
    Nginx
    uni-app mpvue wepy websocket的介绍
    taro 使用taro中的vue来完成小程序的开发
  • 原文地址:https://www.cnblogs.com/gxyandwmm/p/11985056.html
Copyright © 2011-2022 走看看