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()以流的形式返回就不会出现这种问题。
    
    
  • 相关阅读:
    #Leetcode# 700. Search in a Binary Search Tree
    很多很多书上代码
    #Leetcode# 104. Maximum Depth of Binary Tree
    #Leetcode# 12. Integer to Roman
    PAT-2018年冬季考试-乙级
    PAT 1035 插入与归并
    PAT 1058 选择题
    PAT 1052 卖个萌
    CodeForces Round #521 (Div.3) E. Thematic Contests
    2017Nowcoder Girl初赛重现赛
  • 原文地址:https://www.cnblogs.com/landauni/p/7519295.html
Copyright © 2011-2022 走看看