• java发送Http请求


    /**
         * 发送主要方法,异常捕获
         * 
         * @param post
         * @param code
         * @return
         */
        public static String doHttpRequest(String url, String param) {
            
            
    
            PrintWriter out = null;
            BufferedReader in = null;
            String result = "";
            try {
                URL realUrl = new URL(url);
                // 打开和URL之间的连接
              //  URLConnection conn = realUrl.openConnection();
                HttpURLConnection connection = (HttpURLConnection)realUrl.openConnection();
                
                connection.addRequestProperty("Content-Type", "application/json;charset=UTF-8");
                connection.addRequestProperty("User-Agent", "mytest");
                connection.setConnectTimeout(60000);
                connection.setReadTimeout(60000);
                connection.setRequestMethod("POST");
                connection.setDoOutput(true);
                connection.getOutputStream().write(param.getBytes("utf8"));
                
               // connection.setRequestProperty("Content-Type", "application/json");
                int status = connection.getResponseCode();
                
                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
                StringBuffer message = new StringBuffer();
                while (reader.ready()) {
                  message.append(reader.readLine());
                }
                reader.close();
                connection.connect();
                if (status == 200) {
                  return  message.toString();
                }
             
            } catch (Exception e) {
                System.out.println("发送 POST 请求出现异常!"+e);
                e.printStackTrace();
            }
            //使用finally块来关闭输出流、输入流
            finally{
                try{
                    if(out!=null){
                        out.close();
                    }
                    if(in!=null){
                        in.close();
                    }
                }
                catch(IOException ex){
                    ex.printStackTrace();
                }
            }
            return result;
        
        }

    记:
    ①  connection.addRequestProperty("Content-Type", "application/json;charset=UTF-8");如果是json数据这一个属性不添加,会让接收方收不到数据。
    ② 如果json数据以map<"String, object"> 的形式组装,当key对应得value为null的时候,会报错,如果以jsonobject.getbytes()以流的形式返回就不会出现这种问题。
    
    
  • 相关阅读:
    git常用命令
    springcloud 心得记录
    Spring Boot整合RabbitMQ
    docker安装rabbitmq
    Linux按顺序启动多个jar的shell脚本
    idea连接docker实现一键部署
    docker安装mysql
    阿里云CentOS服务器挂载数据盘
    【selenium学习中级篇 -26】HTMLTestRunner生成测试报告
    【selenium学习中级篇 -25】Unittest框架
  • 原文地址:https://www.cnblogs.com/landauni/p/7519295.html
Copyright © 2020-2023  润新知