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()以流的形式返回就不会出现这种问题。
    
    
  • 相关阅读:
    CORS详解
    JBoss 系列九十九:Rest WebService jBPM 6 集成演示样例
    atitit。浏览器缓存机制 and 微信浏览器防止缓存的设计 attilax 总结
    4G时代来临,运营商为谁搭台献唱?
    Pascal&#39;s Triangle II
    cocos2d-x 3.6版连连看载入资源
    SlidingMenu导入编译用法--Eclipse和IDEA
    【解决】hive动态添加partitions不能超过100的问题
    AngularJS clone directive 指令复制
    AndroidStudio文件夹结构视图讲解
  • 原文地址:https://www.cnblogs.com/landauni/p/7519295.html
Copyright © 2011-2022 走看看