考虑以下代码。 connection.connect是多余的,因为我正在做一个url.openConnection()。如果是,那么为什么我们有一个.connect()方法呢?是在关闭连接后重新连接吗?
URL url;
url = new URL(
"http://api.longurl.org/v2/expand?format=json&title=1&user-agent=TwitterProject&url="
+ someURL);
HttpURLConnection connection;
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoInput(true);
connection.connect();
BufferedReader in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String line = null;
String full = "";
while ((line = in.readLine()) != null) {
full = full + line;
}
jsonresponse = JSONObject.fromObject(full);
答案 0 :(得分:2)
public abstract void connect() throws IOException
打开此URL引用的资源的通信链接,如果 这种联系尚未建立。如果连接 连接已被打开时调用方法 (由具有值true的连接字段表示),呼叫是 忽略。
在您的情况下,会忽略通话。
connection = (HttpURLConnection) url.openConnection();// already established connection.