我正在使用 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();
}
}
}
请告诉我在这种情况下什么是合适的?