public static String http(String url, Map<String, String> params) {
// 构建请求参数 String postData = ""; if (params != null && params.size() > 0) {
StringBuilder sb = new StringBuilder(); for (Entry<String, String> e : params.entrySet()) { sb.append(e.getKey()); sb.append("="); sb.append(e.getValue()); sb.append("&"); } postData = sb.toString().substring(0, sb.length() - 1); }
System.out.println("send_url:" + url); System.out.println("send_data:" + postData);
// 尝试发送请求 HttpURLConnection con = null; try { con = (HttpURLConnection) new URL(url).openConnection(); System.out.println(con.getConnectTimeout()); con.setConnectTimeout(60000); System.out.println(con.getConnectTimeout()); // con.setReadTimeout(30000);
con.setRequestMethod("POST"); con.setDoOutput(true); con.setDoInput(true); con.setUseCaches(false); con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// 写数据 OutputStreamWriter osw = new OutputStreamWriter( con.getOutputStream(), "UTF-8"); osw.write(postData); osw.flush(); osw.close();
// 读取返回内容 StringBuilder buffer = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader( con.getInputStream(), "UTF-8")); String temp = null; while ((temp = br.readLine()) != null) { buffer.append(temp); buffer.append("\n"); } return buffer.toString(); } catch (Exception e) {
e.printStackTrace(); return "";
} finally { if (con != null) { con.disconnect(); } }
}
就这么点代码,connection超时时间,感觉设置不上, 虽然写成30秒,但实际还是20秒,愁人, 不知道为啥,问别人也不知道~
以前试过,少于20秒,是可以的。 比如设置为10秒,那么超时就是10秒, 但设置成30秒,它还是20秒~~
|