【问题标题】:Java - How to open one HttpURLConnection for both GET and POSTJava - 如何为 GET 和 POST 打开一个 HttpURLConnection
【发布时间】:2016-11-07 20:22:51
【问题描述】:

请求是从 url 获取内容并正确处理内容(每次都不同),然后将答案发布回相同的 url。当我在执行 GET 方法后尝试 setRequestMethod("POST") 时遇到“无法重置方法:已连接”。我的代码如下

public class MyClass {

    /**
     * @param args
     */

    public MyClass() {};

    public void process() {
        String url = "http://www.somesite.com/";
        String strPage = null;
        int n = 0;

        try{
            URL urlObj = new URL(url);
            HttpURLConnection urlConnection =
                    (HttpURLConnection)urlObj.openConnection();
            InputStream in = urlConnection.getInputStream();

            BufferedReader reader = new BufferedReader(new InputStreamReader(in));

            String strWhole = null;
            while(null != (strPage = reader.readLine())){
                strWhole += strPage;
            }

            //handle content here and calculate result
            ... ...
            //send result below

            urlConnection.setRequestMethod("POST");
            urlConnection.setDoOutput(true);
            String urlParameters = "aa=bb&cc=dd&ee=ff";

            DataOutputStream wr = new DataOutputStream(urlConnection.getOutputStream());
            wr.writeBytes(urlParameters);
            wr.flush();
            wr.close();             

            InputStream in1 = urlConnection.getInputStream();

            BufferedReader reader1 = new BufferedReader(new InputStreamReader(in));


            while(null != (strPage = reader1.readLine())){
                System.out.println(strPage);
            }

            reader1.close();            
        }
        catch(Exception e){
            String exception = e.getMessage();
            System.out.println(exception);
            if (reader != null) {
                reader.close();
            }

            if (reader1 != null) {
                reader1.close();
            }
        }

        return;

    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        MyClass dp = new MyClass();
        dp.process();

    }

}

【问题讨论】:

    标签: java http http-post http-get


    【解决方案1】:

    不可能重用HttpURLConnection 实例。但是documentation 表示,在底层,Java 会为您重用连接:

    JDK 支持 HTTP/1.1 和 HTTP/1.0 持久连接。

    当应用程序完成读取响应正文或应用程序在URLConnection.getInputStream() 返回的InputStream 上调用close() 时,JDK 的 HTTP 协议处理程序将尝试清理连接,如果成功,将连接放入供未来 HTTP 请求重用的连接缓存。

    对 HTTP keep-Alive 的支持是透明的。

    因此,无需手动重用连接。

    【讨论】:

    • 调用 close() 后它不起作用并再次执行 POST,遇到同样的问题。
    • close()之后应该不行,开个新连接openConnection就行了。
    【解决方案2】:

    您必须先设置所有参数。这是我在应用程序中使用的代码:

         HttpURLConnection connection = (HttpURLConnection)new URL(url).openConnection();
         connection.setDoOutput(true);
         connection.setDoInput(true);
         connection.setInstanceFollowRedirects(false);
         connection.setRequestMethod("POST"); 
         connection.setRequestProperty("app_token", "my token"); // optional header you can set with your own data
         connection.setRequestProperty("charset", "utf-8");
         connection.setRequestProperty("Content-Length", String.valueOf(urlParameters.getBytes().length));
         connection.setUseCaches (false);
         DataOutputStream wr = new DataOutputStream(connection.getOutputStream ());
         wr.writeBytes(urlParameters);
         wr.flush();
         wr.close();
         connection.disconnect();
         InputStream is = connection.getInputStream();
         byte[] b = readWithoutSize(is);
         is.close();
    

    readWithoutSize 是:

       public static byte[] readWithoutSize(InputStream is) throws IOException
       {
          ByteArrayOutputStream baos = new ByteArrayOutputStream(4096);
          byte[] buf = new byte[512];
          int leu;
          while ((leu = is.read(buf)) != -1)
             baos.write(buf,0,leu);
          return baos.toByteArray();
       }
    

    【讨论】:

    • @Guiherme 我什么时候应该调用 openConnection()?
    • @Guiherme 谢谢,它对我不起作用。 kgeorgiy 的解决方案正是我所需要的 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-07
    • 2012-02-04
    • 1970-01-01
    • 2019-04-07
    • 2011-07-28
    • 2012-01-01
    相关资源
    最近更新 更多