用HttpURLConnection模拟post请求,不post的问题

 /**
     * post json格式的数据
     * @param requestUrl
     * @param data
     * @param getReutrn
     * @return
     */
    public static String postJsonData(String requestUrl, String data,boolean getReutrn){
        String sTotalString = "";
        try{
            URL url = new URL(requestUrl);
            HttpURLConnection httpconn = (HttpURLConnection) url.openConnection();
            httpconn.setConnectTimeout(ApiConsts.HTTP_CONN_TIMEOUT);
            httpconn.setReadTimeout(ApiConsts.HTTP_READ_TIMEOUT);
            httpconn.setDoInput(true);
            httpconn.setDoOutput(true);
            httpconn.setRequestMethod("POST");
            httpconn.setRequestProperty("Accept", "text/javascript");
            httpconn.setRequestProperty("Content-Type", "text/javascript; charset=" + CommonConst.APP_CHARSET);
            //post json数据
            OutputStreamWriter out = new OutputStreamWriter(httpconn.getOutputStream(), CommonConst.APP_CHARSET); // 指定编码  
            log.info(String.format("%s%s | req=%s | url=%s", LOG_MSG, "postjson",data,requestUrl));
            out.append(data);
            out.flush();
            out.close();if(getReutrn){
                //得到返回结果
         InputStream inPs = httpconn.getInputStream(); BufferedReader l_reader = new BufferedReader(new InputStreamReader(inPs)); String sCurrentLine=""; while ((sCurrentLine = l_reader.readLine()) != null) { sTotalString += sCurrentLine + "\r\n"; } return sTotalString; }else{ return null; } }catch (Exception e) { e.printStackTrace(); log.error(String.format("%s%s", LOG_MSG, "postjson"), e); } return null; }

由于想通过getReturn参数,控制是否读取返回值。

结果,发现当getReturn为true时,请求才会发送出去。一开始有点不明白。代码中的out.flush(); out.close();不是已经把数据flush();出去了吗?为什么请求没有到达服务器。

经过改造后的代码是:

 

/**
     * post json格式的数据
     * @param requestUrl
     * @param data
     * @param getReutrn
     * @return
     */
    public static String postJsonData(String requestUrl, String data,boolean getReutrn){
        String sTotalString = "";
        try{
            URL url = new URL(requestUrl);
            HttpURLConnection httpconn = (HttpURLConnection) url.openConnection();
            httpconn.setConnectTimeout(ApiConsts.HTTP_CONN_TIMEOUT);
            httpconn.setReadTimeout(ApiConsts.HTTP_READ_TIMEOUT);
            httpconn.setDoInput(true);
            httpconn.setDoOutput(true);
            httpconn.setRequestMethod("POST");
            httpconn.setRequestProperty("Accept", "text/javascript");
            httpconn.setRequestProperty("Content-Type", "text/javascript; charset=" + CommonConst.APP_CHARSET);
            //post json数据
            OutputStreamWriter out = new OutputStreamWriter(httpconn.getOutputStream(), CommonConst.APP_CHARSET); // 指定编码  
            log.info(String.format("%s%s | req=%s | url=%s", LOG_MSG, "postjson",data,requestUrl));
            out.append(data);
            out.flush();
            out.close();
            InputStream inPs  = httpconn.getInputStream();
            if(getReutrn){
                //得到返回结果
                BufferedReader l_reader = new BufferedReader(new InputStreamReader(inPs));  
                String sCurrentLine="";
                while ((sCurrentLine = l_reader.readLine()) != null) {  
                    sTotalString += sCurrentLine + "\r\n";    
                }
                return sTotalString;
            }else{
                return null;
            }
        }catch (Exception e) {
            e.printStackTrace();
            log.error(String.format("%s%s", LOG_MSG, "postjson"), e);
        }
        return null;
    }

 

注意两处红色部分的代码。有什么不同。InputStream inPs  = httpconn.getInputStream();这一句,放到if()判断的外面。

这样,请求就到达服务器端了。

后面在这位仁兄的博客中找到答案:http://www.cnblogs.com/guodongli/archive/2011/04/05/2005930.html

博主的文章里面讲到:

InputStream inStrm = httpConn.getInputStream(); // <===注意,实际发送请求的代码段就在这里

 

总结:a:) HttpURLConnection的connect()函数,实际上只是建立了一个与服务器的tcp连接,并没有实际发送http请求。 

    无论是post还是get,http请求实际上直到HttpURLConnection的getInputStream()这个函数里面才正式发送出去。
原来,请求发送是在httpConn.getInputStream();调用时。博主文章讲得好详细,读者可以移步到里面看个研究。

 

posted @ 2013-01-16 17:06  风吹倒了蕉  阅读(1190)  评论(0编辑  收藏  举报