zoukankan      html  css  js  c++  java
  • 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()以流的形式返回就不会出现这种问题。
    
    
  • 相关阅读:
    servlet生命周期和线程安全
    如何保证Redis与数据库的数据一致性
    消息队列高可用、幂等性、顺序性、可靠性传输、堆积问题解决
    如何保证消息队列消息的顺序性
    RabbitMQ 如何保证消息不丢失?
    深入理解MySql事务
    MySQL/mariadb知识点总结
    如何实现一个线程安全的单例,前提是不能加锁
    DUBBO原理、应用与面经总结
    SpringBoot中资源初始化加载的几种方式
  • 原文地址:https://www.cnblogs.com/landauni/p/7519295.html
Copyright © 2011-2022 走看看