工具类
import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.Map; import org.apache.commons.collections.MapUtils; import org.apache.commons.lang.StringUtils; public class HttpUtil { /** * 建立连接 * * @param uri * @param connectTimeout * @param readTimeout * @param params * @return * @throws Exception */ public static HttpURLConnection createPostHttpConn(String uri, int connectTimeout, int readTimeout, Map<String, String> params) throws Exception { URL url = new URL(uri); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setUseCaches(false); conn.setDoInput(true); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.setInstanceFollowRedirects(true); conn.setConnectTimeout(connectTimeout); conn.setReadTimeout(readTimeout); if (MapUtils.isNotEmpty(params)) { for (Map.Entry<String, String> entry : params.entrySet()) { if (StringUtils.isNotBlank(entry.getKey()) && StringUtils.isNotBlank(entry.getValue())) { conn.setRequestProperty(entry.getKey(), entry.getValue()); } } } return conn; } /** * 设置post参数 * * @param conn * @param str * @throws IOException */ public static void setBodyParameter(HttpURLConnection conn, String str) throws IOException { DataOutputStream out = new DataOutputStream(conn.getOutputStream()); out.writeBytes(str); out.flush(); out.close(); } /** * 返回响应结果 * @param conn * @return * @throws Exception */ public static String returnResultStr(HttpURLConnection conn) throws Exception { String result = null; InputStream input = null; if (conn.getResponseCode() == 200) { input = conn.getInputStream(); } else { input = conn.getErrorStream(); } result = new String(readInputStream(input)); return result; } private static byte[] readInputStream(InputStream inStream) throws Exception { ByteArrayOutputStream outStream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = 0; while ((len = inStream.read(buffer)) != -1) { outStream.write(buffer, 0, len); } byte[] data = outStream.toByteArray(); outStream.close(); inStream.close(); return data; } public static String out(String fileName) throws Exception { ByteArrayOutputStream outStream = new ByteArrayOutputStream(); FileInputStream inputStream = new FileInputStream(fileName); int len = 0; byte[] buffer = new byte[1024]; while((len = inputStream.read(buffer)) != -1) { outStream.write(buffer, 0, len); } String result = outStream.toString().trim(); outStream.close(); inputStream.close(); return result; } }