设置常量
1 /** 2 * 建立连接的超时值 3 */ 4 public static final int HTTP_CONNECTION_TIMEOUT = 6 * 1000; 5 /** 6 * 读超时的超时值 7 */ 8 public static final int HTTP_READ_TIMEOUT = 25 * 1000; 9 public static final String UTF_8 = "UTF-8";
httpPostRequest 函数
1 /** 2 * Http Post 请求 3 * 4 * @param requestUrl 5 * 请求地址 6 * @param postJson 7 * 上传数据 8 * @return 如果请求失败返回null 9 * @throws IOException 10 */ 11 public static String httpPostRequest(String requestUrl, String postJson) throws IOException { 12 URL url = new URL(requestUrl); 13 HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 14 connection.setRequestMethod("POST"); 15 connection.setDoInput(true); 16 connection.setDoOutput(true); 17 connection.setUseCaches(false); 18 //设置连接超时时间 19 connection.setConnectTimeout(HTTP_CONNECTION_TIMEOUT); 20 //设置读超时的时间 21 connection.setReadTimeout(HTTP_READ_TIMEOUT); 22 connection.setRequestProperty("Charset", UTF_8); 23 connection.setRequestProperty("Connection", "keep-alive"); 24 connection.setRequestProperty("Content-Type", "application/json"); 25 26 connection.getOutputStream().write(postJson.getBytes()); 27 connection.getOutputStream().flush(); 28 connection.getOutputStream().close(); 29 30 String data = null; 31 if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { 32 InputStream inputStream = connection.getInputStream(); 33 data = new String(FileUtil.readStream(inputStream)); 34 } else { 35 Log.d(TAG, "Post Response Code : " + connection.getResponseCode()); 36 } 37 connection.disconnect(); 38 return data; 39 }