当前位置 : 主页 > 编程语言 > java >

httpUtil(弱网环境会自动尝试3次)

来源:互联网 收集:自由互联 发布时间:2021-06-28
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
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.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;
    }
}
网友评论