使用java创建http请求

package com.hannan.ehu.test.utils;

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

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Iterator;
import java.util.Map;

public class HttpClient {
    private static Logger log = LoggerFactory.getLogger(HttpClient.class);

    /**
     * Get请求(请将需要传递的参数拼接在url后,eg:http://www.baidu.com?name=白白)
     * 如果需要鉴权信息则添加Authorization即可
     * @param httpUrl
     * @return
     */
    public static String doGet(String httpUrl) {
        HttpURLConnection connection = null;
        InputStream is = null;
        BufferedReader br = null;
        String result = null;// 返回结果字符串
        try {
            URL url = new URL(httpUrl);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(15000);
            connection.setReadTimeout(60000);
            connection.connect();
            if (connection.getResponseCode() == 200) {
                is = connection.getInputStream();
                br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                StringBuffer sbf = new StringBuffer(); // 存放数据
                String temp = null;
                while ((temp = br.readLine()) != null) {
                    sbf.append(temp + "\r\n");
                }
                result = sbf.toString();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            log.error("http的Get请求出现异常:", e.getCause());
        } finally {
            // 关闭资源
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            connection.disconnect();// 关闭远程连接
        }
        return result;
    }

    /**
     * json类型post请求(可更具注释自行修改)
     * 如果需要鉴权信息则,放开代码下的Authorization即可
     * @param httpUrl 请求的地址
     * @param params  请求的参数
     * @return
     */
    private static String doPost(String httpUrl, String params) {
        HttpURLConnection connection = null;
        InputStream is = null;
        OutputStream os = null;
        BufferedReader br = null;
        String result = null;
        try {
            URL url = new URL(httpUrl);
            connection = (HttpURLConnection) url.openConnection(); // 通过远程url连接对象打开连接
            connection.setRequestMethod("POST"); // 设置连接请求方式
            connection.setConnectTimeout(15000); // 设置连接主机服务器超时时间:15000毫秒
            connection.setReadTimeout(60000);  // 设置读取主机服务器返回数据超时时间:60000毫秒
            connection.setDoOutput(true); // 默认值为:false,当向远程服务器传送数据/写数据时,需要设置为true
            connection.setDoInput(true); // 默认值为:true,当前向远程服务读取数据时,设置为true,该参数可有可无
            connection.setRequestProperty("Content-Type", "application/json"); // 设置传入参数的格式为json,而不是默认的请求参数 name1=value1&name2=value2 的形式。
//			connection.setRequestProperty("Authorization", "Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0"); // 设置鉴权信息:Authorization: Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0
            /**
             * String contentType = conn.getHeaderField("Content-Type"); 通过getHeaderField()方法可以读取响应头
             * conn.setRequestProperty("Authorization", "token 111"); 设置鉴权信息:Authorization: token 111(即添加token)
             * conn.setRequestProperty("Cookie",StringUtils.join(cookieManager.getCookieStore().getCookies(), ";")); 添加cookie
             * String cookiesHeader = conn.getHeaderField("Set-Cookie");List<HttpCookie> cookies = HttpCookie.parse(cookiesHeader); 获取cookie
             * Optional<HttpCookie> usernameCookie = cookies.stream().findAny().filter(cookie -> cookie.getName().equals("username"));检查cookie中是否含有username
             * connection.getResponseCode() 得到响应码 200 500 等  需要写在子类中
             * conn.setInstanceFollowRedirects(false); 处理重定向  需要写在子类中
             */
            os = connection.getOutputStream(); // 通过连接对象获取一个输出流
            os.write(params.getBytes()); // 通过输出流对象将参数写出去/传输出去,它是通过字节数组写出的
            if (connection.getResponseCode() == 200) { // 通过连接对象获取一个输入流,向远程读取
                is = connection.getInputStream();
                br = new BufferedReader(new InputStreamReader(is, "UTF-8")); // 对输入流对象进行包装:charset根据工作项目组的要求来设置
                StringBuffer sbf = new StringBuffer();
                String temp = null;
                while ((temp = br.readLine()) != null) { // 循环遍历一行一行读取数据
                    sbf.append(temp);
                    sbf.append("\r\n");
                }
                result = sbf.toString();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally { // 关闭资源
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    log.error("http的POST请求出现异常:", e.getCause());
                }
            }
            if (null != os) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            // 断开与远程地址url的连接
            connection.disconnect();
        }
        return result;
    }

    /**
     * http模拟form提交表单
     *
     * @param urlStr    请求地址(不能为空)
     * @param filename  文件名称(当文件名称为空时,byteArray也为空,不为空时filename为含有文件类型后缀的文件名称)
     * @param byteArray 文件的字节流(不能为空)
     * @param textMap   表单非文件参数(可为空)
     * @return result 请求的结果(String)
     */
    @SuppressWarnings("rawtypes")
    public static String doFormPost(String urlStr, String filename, byte[] byteArray, Map<String, Object> textMap) {
        DataInputStream in = new DataInputStream(new ByteArrayInputStream(byteArray));
        String res = "";
        HttpURLConnection conn = null;
        // boundary就是request头和上传文件内容的分隔符
        String BOUNDARY = "---------------------------123821742118716";
        try {
            URL url = new URL(urlStr);
            conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(30000);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("User-Agent",
                    "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)");
            conn.setRequestProperty("Content-Type",
                    "multipart/form-data; boundary=" + BOUNDARY);
            OutputStream out = new DataOutputStream(conn.getOutputStream());
            // text
            if (textMap != null) {
                StringBuffer strBuf = new StringBuffer();
                Iterator iter = textMap.entrySet().iterator();
                while (iter.hasNext()) {
                    Map.Entry entry = (Map.Entry) iter.next();
                    String inputName = (String) entry.getKey();
                    String inputValue = (String) entry.getValue();
                    if (inputValue == null) {
                        continue;
                    }
                    strBuf.append("\r\n").append("--").append(BOUNDARY)
                            .append("\r\n");
                    strBuf.append("Content-Disposition: form-data; name=\""
                            + inputName + "\"\r\n\r\n");
                    strBuf.append(inputValue);
                }
                out.write(strBuf.toString().getBytes());
            }

            if (filename != null) {
                //没有传入文件类型,同时根据文件获取不到类型,默认采用application/octet-stream
                String contentType = "application/octet-stream";
                if (filename.endsWith(".png")) {
                    contentType = "image/png";
                } else if (filename.endsWith(".jpg") || filename.endsWith(".jpeg") || filename.endsWith(".jpe")) {
                    contentType = "image/jpeg";
                } else if (filename.endsWith(".gif")) {
                    contentType = "image/gif";
                } else if (filename.endsWith(".ico")) {
                    contentType = "image/image/x-icon";
                }
                StringBuffer strBuf = new StringBuffer();
                strBuf.append("\r\n").append("--").append(BOUNDARY)
                        .append("\r\n");
                strBuf.append("Content-Disposition: form-data; name=\""
                        + "file" + "\"; filename=\"" + filename
                        + "\"\r\n");
                System.out.println("file" + "," + filename);

                strBuf.append("Content-Type:" + contentType + "\r\n\r\n");
                out.write(strBuf.toString().getBytes());
            }
            /**
             * 最终也得含有form结尾
             */
            int bytes = 0;
            byte[] bufferOut = new byte[1024];
            while ((bytes = in.read(bufferOut)) != -1) {
                out.write(bufferOut, 0, bytes);
            }
            in.close();
            byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
            out.write(endData);
            out.flush();
            out.close();
            // 读取返回数据
            StringBuffer strBuf2 = new StringBuffer();
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    conn.getInputStream()));
            String line = null;
            while ((line = reader.readLine()) != null) {
                strBuf2.append(line).append("\n");
            }
            res = strBuf2.toString();
            reader.close();
            reader = null;
        } catch (Exception e) {
            log.error("发送POST请求出错:", e.getCause());
            e.printStackTrace();
        } finally {
            if (conn != null) {
                conn.disconnect();
                conn = null;
            }
        }
        return res;
    }
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值