HttpURLConnection请求方式get,post分析

HttpURLConnection请求方式get,post分析

1.post请求方式

  如果现在有个需求,是需要把图片上传到自己的服务器。如果是在普通的客户端实现,就form表单post请求提交图片多媒体信息。现在使用HttpURLConnection 服务器端提交post请求实现,所以我们先要分析客户端post请求示例,如下图所示:
在这里插入图片描述
  搜狗浏览器F12开发者模式,查看请求,如下图:
在这里插入图片描述
  通过上面的图片,可以很直观的看到上传一个文件时候的POST参数以及Request Headers的内容。
其中就有:Content-Type multipart/form-data; boundary=----WebKitFormBoundary53Ou9XKKFPAjbtwg
我们使用表单上传文件时,必须让 表单的 enctyped 等于 multipart/form-data。所以在上传大文件或图片时,我们就需要设置Content-Type的方式上传。
在这里插入图片描述
  上面的图片可以通过对比看出:
  区别点在Content-type,上传txt文件时为:text/plain, 而上传图片时为:image/jpeg
Content-Type表明信息类型,缺省值为" text/plain"。它包含了主要类型(primary type)和次要类型(subtype)两个部分,两者之间用"/"分割。主要类型有9种,分别是application、audio、example、image、message、model、multipart、text、video。
  每一种主要类型下面又有许多次要类型:
  text/plain:纯文本,文件扩展名.txt
  text/html:HTML文本,文件扩展名.htm和.html
  image/jpeg:jpeg格式的图片,文件扩展名.jpg
  image/gif:GIF格式的图片,文件扩展名.gif
  audio/x-wave:WAVE格式的音频,文件扩展名.wav
  audio/mpeg:MP3格式的音频,文件扩展名.mp3
  video/mpeg:MPEG格式的视频,文件扩展名.mpg
  application/zip:PK-ZIP格式的压缩文件,文件扩展名.zip

通过上面的介绍,我们可以总结出,如果要模拟表单实现multipart上传,则需要做到以下几点:

1.请求方式post

2.请求头的Content-type为multipart/form-data;boundary=—1293834(任意几个数字);

  1. a.请求体中需要先以"-----1293834\r\n(\r\n的作用是换行)"来分隔,

    b.然后写入Content-Disposition:form-data;name=“iamge(此处需要与服务器约定)”;filename=“test.jpg”;

    c.Content-Type: image/jpeg(这里根据自己情况来决定)

    d.图片或文件的byte[]数组。

    e.最后以"-----1293834–\r\n"结尾。

4.最后读取服务器的返回信息,来判断是否成功。

细节决定成败:2中的"—1293834"与3中的"-----1293834"差2个"–"

    public static String formUpload(String urlStr, Map<String, String> textMap, Map<String, InputStream> fileMap)
    {
        String res = "";
        HttpURLConnection conn = null;
        String BOUNDARY = "---------------------------123821742118716"; //boundary就是request头和上传文件内容的分隔符
        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());
            // textMap:如果传送的是文本内容
            if (textMap != null)
            {
                StringBuffer strBuf = new StringBuffer();
                Iterator<Map.Entry<String, String>> iter = textMap.entrySet().iterator();
                while (iter.hasNext())
                {
                    Map.Entry<String, String> 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());
            }
            //fileMap:如果传送的是文件流
            if (fileMap != null)
            {
                Iterator<Map.Entry<String, InputStream>> iter = fileMap.entrySet().iterator();
                while (iter.hasNext())
                {
                    Map.Entry<String, InputStream> entry = iter.next();
                    String inputName = (String) entry.getKey();
                    FileInputStream inputValue = (FileInputStream) entry.getValue();
                    if (inputValue == null)
                    {
                        continue;
                    }
                    String contentType = "image/jpeg";
                    StringBuffer strBuf = new StringBuffer();
                    strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
                    strBuf.append("Content-Disposition: form-data; name=\"" + inputName + "\"; filename=\"" + inputName
                            + "\"\r\n");
                    strBuf.append("Content-Type:" + contentType + "\r\n\r\n");
                    IOUtils.write(strBuf.toString().getBytes(), out);
                    DataInputStream in = new DataInputStream(inputValue);
                    IOUtils.copy(in, out);
                }
            }
            byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
            IOUtils.write(endData, out);
            // 读取返回数据
            res = IOUtils.toString(conn.getInputStream(), "utf-8");
        } catch (Exception e)
        {
            e.printStackTrace();
        } finally
        {
            //最后关闭链接
            if (conn != null)
            {
                conn.disconnect();
                conn = null;
            }
        }
        return res;
    }
1.get请求方式
    public static String getTree(String path)
    {
        try
        {

            //对应GET请求,要把请求信息拼接在url后面
            URL url = new URL(path);
            //调用url的openConnection()方法,获得连接对象
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            //设置HttpURLConnection的属性
            conn.setRequestMethod("GET");
            conn.setReadTimeout(5000);
            conn.setConnectTimeout(5000);
            //只是建立一个连接, 并不会发送真正http请求  (可以不调用)
            conn.connect();
            //通过响应码来判断是否连接成功
            if (conn.getResponseCode() == 200)
            {
                //获得服务器返回的字节流
                InputStream is = conn.getInputStream();
                String result = IOUtils.toString(is, "utf-8");
                return result;
            }
            conn.disconnect();
        } catch (Exception e)
        {
            e.printStackTrace();
        }
        return null;
    }
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值