实现一个HttpRequest请求类

本文承接上一篇文章,路径如下:记录一个Request父类

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.util.Iterator;
import java.util.Map;

import jp.co.fujixerox.xcp.sdcc.store.http.Requestor;
import jp.co.fujixerox.xcp.sdcc.store.log.SystemConsole;

/**
 * HttpRequestor tools class
 * 
 * @author HuangSL
 * @since 2018/05/30
 * @version 1.0.0
 * 
 */
public class HttpRequestor extends Requestor {

    /**
     * Do GET request
     * 
     * @param url
     *            <String>Url path
     * @return InputStream
     * 
     * @author HuangSL
     * @throws Exception
     * @since 2018/05/10
     */
    public InputStream doGet(String url) throws Exception {
        SystemConsole.info("[" + this.getClass().getName() + ".doGet(" + url + ")]start!");

        InputStream inputStream = null;
        HttpURLConnection httpURLConnection = (HttpURLConnection) this.openConnection(url);

        try {
            httpURLConnection.setRequestMethod("GET");

            // 响应失败
            if (httpURLConnection.getResponseCode() >= 300) {
                String msg = "HTTP Request is not success, Response code is " + httpURLConnection.getResponseCode();
                SystemConsole.error("[" + this.getClass().getName() + ".doGet]" + msg);
                throw new Exception(msg);
            }

            // 接收响应流
            inputStream = httpURLConnection.getInputStream();
        } catch (Exception e) {
            e.printStackTrace();
            httpURLConnection.disconnect();

            if (inputStream != null) {
                inputStream.close();
            }
        }

        SystemConsole.info("[" + this.getClass().getName() + ".doGet(" + url + ")]end!");
        return inputStream;
    }

    /**
     * Get text by get request
     * 
     * @param url
     *            <String>Url path
     * 
     * @return <String>Response text
     * @throws Exception
     * 
     * @author HuangSL
     * @since 2018/05/30
     */
    public String getText(String url) throws Exception {
        SystemConsole.info("[" + this.getClass().getName() + ".getText(" + url + ")]start!");
        InputStream inputStream = null;
        BufferedReader reader = null;
        try {

            inputStream = this.doGet(url);
            if (inputStream == null) {
                SystemConsole.error("[" + this.getClass().getName() + ".doGet]Connect the server failed!");
                return null;
            }

            reader = new BufferedReader(new InputStreamReader(inputStream));
            StringBuilder builder = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
            SystemConsole.info("[" + this.getClass().getName() + ".getText(" + url + ")]end!");
            return builder.toString();

        } catch (Exception e) {
            e.printStackTrace();
            return null;

        } finally {

            if (inputStream != null) {
                inputStream.close();
            }

            if (reader != null) {
                reader.close();
            }
        }
    }

    /**
     * Do POST request
     * 
     * @param url
     *            <String>url path
     * @param paramMap
     *            <Map>parameters
     * 
     * @return <String>Response text
     * @throws IOException
     * 
     * @author HuangSL
     * @since 2018/05/13
     */
    public String doPost(String url, Map<String, Object> paramMap) throws IOException {
        SystemConsole.info("[" + this.getClass().getName() + ".doPost(" + url + ", paramMap)]start!");

        StringBuilder paramBuilder = new StringBuilder();
        if (paramMap != null) {
            Iterator<String> iterator = paramMap.keySet().iterator();
            String key;
            String value;
            while (iterator.hasNext()) {
                key = iterator.next();
                value = (String) paramMap.get(key);
                if (value == null) {
                    value = "";
                }

                paramBuilder.append(key).append("=").append(value);
                if (iterator.hasNext()) {
                    paramBuilder.append("&");
                }
            }
        }

        SystemConsole.info("[" + this.getClass().getName() + ".doPost]parameters:" + paramBuilder.toString());

        this.setDoOutpt(true);
        this.setContentType("application/x-www-form-urlencoded");
        HttpURLConnection httpURLConnection = (HttpURLConnection) this.openConnection(url);

        httpURLConnection.setRequestMethod("POST");
        httpURLConnection.setRequestProperty("Content-Length", String.valueOf(paramBuilder.length()));

        OutputStream outputStream = null;
        OutputStreamWriter outputStreamWriter = null;
        InputStream inputStream = null;
        BufferedReader bufferedReader = null;
        String line;
        StringBuilder builder = new StringBuilder();
        try {
            // 设置 post 参数
            outputStream = httpURLConnection.getOutputStream();
            outputStreamWriter = new OutputStreamWriter(outputStream);
            outputStreamWriter.write(paramBuilder.toString());
            outputStreamWriter.flush();
            outputStreamWriter.close();

            httpURLConnection.connect();

            // 响应失败
            if (httpURLConnection.getResponseCode() > 300) {
                String msg = "HTTP Request is not success, Response code is " + httpURLConnection.getResponseCode();
                SystemConsole.error("[" + this.getClass().getName() + ".doPost]" + msg);
                throw new Exception(msg);
            }

            // 接收响应流
            inputStream = httpURLConnection.getInputStream();
            bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

            while ((line = bufferedReader.readLine()) != null) {
                builder.append(line);
            }
        } catch (Exception e) {
            e.printStackTrace();

        } finally {

            if (outputStream != null) {
                outputStream.close();
            }

            if (outputStreamWriter != null) {
                outputStreamWriter.close();
            }

            if (inputStream != null) {
                inputStream.close();
            }

            if (bufferedReader != null) {
                bufferedReader.close();
            }

            httpURLConnection.disconnect();
        }

        SystemConsole.info("[" + this.getClass().getName() + ".doPost(" + url + ", paramMap)]end!");
        return builder.toString();
    }
}

猜你喜欢

转载自blog.csdn.net/hsl0530hsl/article/details/80525327
今日推荐