以优化方式进行多个相同的http请求

时间:2019-04-26 05:56:53

标签: java java-websocket

我的代码看起来像

for (int i = 0; i < len; i++) {
    getResponse();
}

我正在for循环中发出请求。不想每次都打开请求并希望优化这种更好的方法。我们如何才能更好地做到这一点?

public static void getReponse() {
    try {
        // Construct data
        String data = URLEncoder.encode("key1", "UTF-8") + "=" + URLEncoder.encode("value1", "UTF-8");
        data += "&" + URLEncoder.encode("key2", "UTF-8") + "=" + URLEncoder.encode("value2", "UTF-8");

        // Send data
        URL url = new URL("http://hostname:80/cgi");
        URLConnection conn = url.openConnection();
        conn.setDoOutput(true);
        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
        wr.write(data);
        wr.flush();

        // Get the response
        BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line;
        while ((line = rd.readLine()) != null) {
            // Process line...
        }
        wr.close();
        rd.close();
    } catch (Exception e) {}
}

0 个答案:

没有答案