gistfile1.txt import net.sf.json.JSONObject;import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;import org.apache.commons.httpclient.HttpClient;import org.apache.commons.httpclient.HttpStatus;import org.apache.commons.httpcli
import net.sf.json.JSONObject; import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.methods.StringRequestEntity; import org.apache.commons.httpclient.params.HttpMethodParams; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringUtils; import java.io.IOException; public class HttpRestUtil { /** * Http请求 * * @param url 请求地址 * @param param 请求参数 {net.sf.json.JSONObject} * @param rerty 重试次数 * @return 返回结果 {net.sf.json.JSONObject} */ public static JSONObject post(String url, JSONObject param, int rerty) throws IOException { JSONObject result = new JSONObject(); HttpClient client = new HttpClient(); PostMethod method = new PostMethod(url); method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(rerty, false)); StringRequestEntity requestEntity = new StringRequestEntity(param.toString(), "application/json", "UTF-8"); method.setRequestEntity(requestEntity); int statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { throw new IOException("服务器不可用:" + method.getStatusLine()); } String res = IOUtils.toString(method.getResponseBodyAsStream(), "UTF-8"); if (StringUtils.isNotEmpty(res)) { result = JSONObject.fromObject(res); } method.releaseConnection(); return result; } }