简体   繁体   English

Java-如何为GET和POST打开一个HttpURLConnection

[英]Java - How to open one HttpURLConnection for both GET and POST

The request is to GET content from url and handle the content(different every time) properly, then POST the answer back to the same url. 请求是从url获取内容并正确处理内容(每次都不同),然后将答案回传到相同的url。 I encounter "Can't reset method: already connected" when I try to setRequestMethod("POST") after GET method executed. 我在执行GET方法后尝试setRequestMethod(“ POST”)时遇到“无法重置方法:已连接”。 My code as below 我的代码如下

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();

    }

}

It is impossible to reuse HttpURLConnection instance. 重用HttpURLConnection实例是不可能的。 But documentation says that under the hood, Java reuses connections for you: 但是文档说,在幕后,Java为您重用了连接:

The JDK supports both HTTP/1.1 and HTTP/1.0 persistent connections. JDK同时支持HTTP / 1.1和HTTP / 1.0持久连接。

When the application finishes reading the response body or when the application calls close() on the InputStream returned by URLConnection.getInputStream() , the JDK's HTTP protocol handler will try to clean up the connection and if successful, put the connection into a connection cache for reuse by future HTTP requests. 当应用程序完成读取响应主体时,或者当应用程序调用URLConnection.getInputStream()返回的InputStream上的close()时,JDK的HTTP协议处理程序将尝试清理连接,如果成功,则将连接放入连接缓存中供将来的HTTP请求重用。

The support for HTTP keep-Alive is done transparently. 对HTTP keep-Alive的支持是透明完成的。

Therefore, there is no need to reuse connections manually. 因此,无需手动重用连接。

You must set all parameters first. 您必须首先设置所有参数。 Here's a code i use in my application: 这是我在应用程序中使用的代码:

     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();

The readWithoutSize is: 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();
   }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM