HTTP请求工具类,完成简单的GET POST请求(为了熟悉相关API)。

HTTP请求工具类,完成简单的GET POST请求.代码很简单。


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.*;
import java.util.HashMap;
import java.util.Map;

/**
 * @author WangShiXiang
 * @date 2018/7/10
 **/
public class RequestHttp {

    Logger LOG= LoggerFactory.getLogger(RequestHttp.class);

    private String urlStr=null;

    private HttpURLConnection connection=null;

    private Map<String,String> cookie=null;

    private Map<String,String> param=null;

    private Map<String,String> header=null;

    private String body=null;

    private String result=null;

    private int connectTimeOut=30000;

    private int readTimeOut=30000;

    private int code=-1;

    public static final int SUCCESS_CODE=200;

    private String charSetName="UTF-8";

    private String errorMessage=null;

    /**
     * 总共请求几次,设置3就是网络不好时总共请求3次
     * 默认请求1次 不重试
     */
    private int retry=1;

    public static RequestHttp buidRequest(String urlStr){

        return new RequestHttp(urlStr);
    }

    private RequestHttp(String urlStr){
        this.urlStr=urlStr;
    }

    public RequestHttp setParam(String key,String value){
        if (param==null){
            param=new HashMap<>(16);
        }
        param.put(key,value);
        return this;
    }

    public RequestHttp setCookie(String key,String value){
        if (cookie==null){
            cookie=new HashMap<>(16);
        }
        cookie.put(key,value);
        return this;
    }

    public RequestHttp setHeader(String key,String value){
        if (header==null){
            header=new HashMap<>(16);
        }
        header.put(key,value);
        return this;
    }

    public String getResult(){
        return result;
    }

    public int getResponseCode(){
        return code;
    }

    public RequestHttp setConnectTimeOut(int connectTimeOut) {
        this.connectTimeOut = connectTimeOut;
        return this;
    }

    public RequestHttp setReadTimeOut(int readTimeOut) {
        this.readTimeOut = readTimeOut;
        return this;
    }

    public String getErrorMessage() {
        return errorMessage;
    }
    public RequestHttp post(){
        for(int i=0;i<retry;i++){
             try {
                 postP();
             }catch (SocketException e){
                    LOG.info("第{}次请求失败,请求url为:{}",i+1,urlStr);
                    if (i==retry-1){
                        e.printStackTrace();
                    }
             } catch (IOException e) {
                 e.printStackTrace();
                 return this;
             }
        }

        return this;
    }

    private void postP() throws IOException {
        URL url=null;
        try {
            url=new URL(urlStr);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        if (url==null){
            throw new MalformedURLException("生成的url为null");
        }
        try {
            connection= (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setConnectTimeout(connectTimeOut);
            connection.setReadTimeout(readTimeOut);
            setCookie();
            setHeader();
            setParam(false);
            connection.setDoOutput(true);
            connection.setDoInput(true);
            OutputStream outputStream=connection.getOutputStream();
            DataOutputStream dataOutputStream=new DataOutputStream(outputStream);
            dataOutputStream.writeBytes(body);
            dataOutputStream.flush();
            resolverConnection();
        } catch (IOException e) {
            throw e;
        }
    }
    public RequestHttp get(){
        for(int i=0;i<retry;i++){
            try {
                getP();
            }catch (SocketException e){
                LOG.info("第{}次请求失败,请求url为:{}",i+1,urlStr);
                if (i==retry-1){
                    e.printStackTrace();
                }
            } catch (IOException e) {
                e.printStackTrace();
                return this;
            }
        }

        return this;
    }
    private RequestHttp getP() throws IOException {
        URL url=null;
        setParam(true);
        setCookie();
        try {
            url=new URL(urlStr);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        if (url==null){
            return this;
        }
        try {
            connection= (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(connectTimeOut);
            connection.setReadTimeout(readTimeOut);
            setCookie();
            setHeader();
            resolverConnection();
        } catch (IOException e) {
           throw e;
        }


        return this;
    }

    private void setHeader(){
        if (header!=null){
            header.keySet().forEach(key->{connection.setRequestProperty(key,header.get(key));});
        }
    }
    private void setCookie(){
        if (cookie!=null){
            StringBuilder sb =new StringBuilder();
            cookie.keySet().forEach(key->{sb.append(key).append("=").append(cookie.get(key));});
            connection.setRequestProperty("Cookie", sb.toString());
        }
    }
    private void setParam(boolean ifGet){
        if (param!=null&&body==null){
            StringBuilder sb=new StringBuilder();
            if (ifGet){
                sb.append(urlStr).append("?");
            }
            param.keySet().forEach(key->{
                sb.append(key).append("=").append(param.get(key)).append("&");
            });
            if (ifGet){
                urlStr=sb.toString();
            }else {
                body=sb.toString();
            }
        }
    }

    public RequestHttp setBody(String body) {
        if (param==null) {
            this.body = body;
        }
        return this;
    }

    /**
     * 用来设置重试次数
     * @param retry 重试次数
     * @return 返回RequestHttp
     */
    public RequestHttp setRetry(int retry) {
        this.retry = retry;
        return this;
    }

    /**
     * 请求后用来解析数据
     * @throws IOException
     */
    private void resolverConnection() throws IOException {
        if (connection.getResponseCode()==SUCCESS_CODE) {
            code=SUCCESS_CODE;
            InputStream inputStream=connection.getInputStream();
            ByteArrayOutputStream outputStream=new ByteArrayOutputStream();
            byte[] buf=new byte[1024];
            int count;
            while((count=inputStream.read(buf))!=-1) {
                outputStream.write(buf, 0, count);
            }
            result=outputStream.toString(charSetName);
        }else {
            InputStream inputStream=connection.getErrorStream();
            ByteArrayOutputStream outputStream=new ByteArrayOutputStream();
            byte[] buf=new byte[1024];
            int count;
            while((count=inputStream.read(buf))!=-1) {
                outputStream.write(buf, 0, count);
            }
            errorMessage=outputStream.toString(charSetName);
            code=connection.getResponseCode();
        }
    }


}

 

转载于:https://my.oschina.net/wang520/blog/1844873

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值