import java.net.HttpURLConnection; //导入方法依赖的package包/类
/**
* Initial the connection for POST and GET method.
*
* @param connection
* @param method
* @param requestProperties
* @param connectTimeOut
* @param readTimeOut
* @throws IOException
*/
private static void initConnection(HttpURLConnection connection, String method,
Map requestProperties, Long connectTimeOut, Long readTimeOut) throws IOException {
if (connection != null) {
connection.setUseCaches(false);
connection.setDefaultUseCaches(false);
connection.setDoInput(true);
if (method != null && method.trim().length() > 0) {
try {
connection.setRequestMethod(method);
} catch (ProtocolException e) {
throw new IOException("Set Request Method Error: " + e);
}
if (SEND_METHOD_POST.equals(method)) {
connection.setDoOutput(true);
}
} else {
throw new IOException("Error Method Parameter: " + method);
}
if (requestProperties != null && requestProperties.size() > 0) {
String key, value;
for (Map.Entry tempEntry : requestProperties.entrySet()) {
key = tempEntry.getKey();
value = tempEntry.getValue();
connection.setRequestProperty(key, value);
}
}
if (connectTimeOut != null && readTimeOut != null) {
System.setProperty("sun.net.client.defaultConnectTimeout", connectTimeOut.toString());
System.setProperty("sun.net.client.defaultReadTimeout", readTimeOut.toString());
connection.setConnectTimeout(connectTimeOut.intValue());
connection.setReadTimeout(readTimeOut.intValue());
}
connection.setRequestProperty("User-Agent", "Mozilla/MSIE");
} else {
throw new IOException("Error HttpURLConnection Parameter connection is null.");
}
}