0

我正在使用 HttpUrlConnect 将数据发布到 webservice 。每当有任何记录事件调用时,都会发生这种数据发布。(所以这是连续的)

我对此有疑问,我是否应该使用相同的 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();
            }

        }

    }

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

4

1 回答 1

3

HttpURLConnection的 javadoc 说:

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

因此,尽管在后台连接可能相同,但您应该为每个请求使用一个新实例。

于 2013-07-02T04:23:33.390 回答