我应该使用相同的HttpUrlconnection还是每次都定义一个新的?

时间:2013-07-02 04:06:57

标签: java

我正在使用HttpUrlConnect将数据发布到Web服务。 只要有任何记录事件被调用,就会发生这种数据发布。(所以这是连续的)

我对此有疑问,我应该使用相同的HttpURLConnection,如下所示

private HttpURLConnection getConnection() throws Exception {
        URL url = new URL("http://localhost:8080/RestTest/ajax/user_info");
        HttpURLConnection conn = null;
        conn = (HttpURLConnection) url.openConnection();
        return conn;
    }

    public void execute() throws Exception {
        OutputStream os = null;
        try {

            HttpURLConnection conn = null;


            conn = getConnection();

            conn.setDoOutput(true);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json");

            String input = "{\\\"qty\\\":100,\\\"name\\\":\\\"sdsfds ddd\\\"}";

            os = conn.getOutputStream();
            os.write(input.getBytes());
            os.flush();
            conn.getInputStream();


        } catch (Exception e) {
            e.printStackTrace();
        }

        finally {
            if (os != null) {
                os.close();
            }

        }

    }

或者我应该定义每周的连接,如下所示??

public void execute() throws Exception {
        OutputStream os = null;
        HttpURLConnection conn = null;
        try {
            URL url = new URL("http://localhost:8080/RestTest/ajax/user_info");

            conn = (HttpURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json");
            String input = "{\\\"qty\\\":100,\\\"name\\\":\\\"sdsfds ddd\\\"}";
            os = conn.getOutputStream();
            os.write(input.getBytes());
            os.flush();
            conn.getInputStream();

        } catch (Exception e) {
            e.printStackTrace();
        }

        finally {
            conn.disconnect();
            if (os != null) {
                os.close();
            }

        }

    }

请告诉我在这种情况下适合什么?

1 个答案:

答案 0 :(得分:4)

HttpURLConnection的javadoc说:

  

每个HttpURLConnection实例用于发出单个请求,但与HTTP服务器的基础网络连接可能会被其他实例透明地共享。

所以,虽然在后台连接可能是相同的,但你应该为每个请求使用一个新的intance。