public class HttpUtil { static Properties prop = System.getProperties(); static { try { Properties prop = System.getProperties(); InputStream in = HttpUtil.class.getClassLoader() .getResourceAsStream("util.properties"); prop.load(in); } catch (IOException e) { e.printStackTrace(); } } public static String get(String url) { String response = null; Map<String, String> result = new HashMap<String, String>(); HttpClient client = new HttpClient(); String serverurl = prop.getProperty("http.serverurl"); GetMethod method = new GetMethod(serverurl + url); try { // 执行方法返回状态码 int statusCode = client.executeMethod(method); // 返回的信息 response = method.getResponseBodyAsString(); result.put("statuscode", Integer.toString(statusCode)); result.put("response", response); System.out.println(response); } catch (HttpException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { // 无论响应与否都要关闭连接 method.releaseConnection(); } return response; } public static String post(String url, Map<String, Object> data) { Map<String, Object> ret = new HashMap<String, Object>(); String response = null; HttpClient client = new HttpClient(); String serverurl = prop.getProperty("http.serverurl"); PostMethod method = new PostMethod(serverurl + url); method.addRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"); try { // 设置参数 for (Map.Entry<String, Object> entry : data.entrySet()) { method.addParameter(new NameValuePair(entry.getKey(), String .valueOf(entry.getValue()))); } // 执行方法返回状态码 int statusCode = client.executeMethod(method); // 返回的信息 response = method.getResponseBodyAsString(); ret.put("statuscode", statusCode); ret.put("response", response); } catch (HttpException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { // 无论响应与否都要关闭连接 method.releaseConnection(); } return response; } public static Map<String, Object> post(String url, String xml) { Map<String, Object> result = new HashMap<String, Object>(); HttpClient client = new HttpClient(); String serverurl = prop.getProperty("http.serverurl"); PostMethod method = new PostMethod(serverurl + url); method.setRequestHeader("Content-type", "text/xml; charset=UTF-8"); try { RequestEntity entity = new StringRequestEntity(xml, "text/xml", "iso-8859-1"); method.setRequestEntity(entity); // 执行方法返回状态码 int statusCode = client.executeMethod(method); result.put("statuscode", Integer.toString(statusCode)); // 若是转发301、302 if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) { // 从头中取出转向的地址 Header locationHeader = method.getResponseHeader("location"); String location = locationHeader.getValue(); result.put("redirect", location); } else { // 返回的信息 result.put("response", method.getResponseBodyAsString()); } } catch (HttpException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { // 无论响应与否都要关闭连接 method.releaseConnection(); } return result; } }