欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java HttpURLConnection 发送文件和字符串信息

程序员文章站 2023-12-13 20:23:46
java httpurlconnection 发送文件和字符串信息 以文件的形式传参 /** * 通过拼接的方式构造请求内容,实现参数传输以及文件传...

java httpurlconnection 发送文件和字符串信息

以文件的形式传参

/**
   * 通过拼接的方式构造请求内容,实现参数传输以及文件传输
   * 
   * @param actionurl 访问的服务器url
   * @param params 普通参数
   * @param files 文件参数
   * @return
   * @throws ioexception
   */
  public static void post(string actionurl, map<string, string> params, map<string, file> files) throws ioexception
  {

    string boundary = java.util.uuid.randomuuid().tostring();
    string prefix = "--", linend = "\r\n";
    string multipart_from_data = "multipart/form-data";
    string charset = "utf-8";

    url uri = new url(actionurl);
    httpurlconnection conn = (httpurlconnection) uri.openconnection();
    conn.setreadtimeout(5 * 1000); // 缓存的最长时间
    conn.setdoinput(true);// 允许输入
    conn.setdooutput(true);// 允许输出
    conn.setusecaches(false); // 不允许使用缓存
    conn.setrequestmethod("post");
    conn.setrequestproperty("connection", "keep-alive");
    conn.setrequestproperty("charsert", "utf-8");
    conn.setrequestproperty("content-type", multipart_from_data + ";boundary=" + boundary);

    // 首先组拼文本类型的参数
    stringbuilder sb = new stringbuilder();
    for (map.entry<string, string> entry : params.entryset())
    {
      sb.append(prefix);
      sb.append(boundary);
      sb.append(linend);
      sb.append("content-disposition: form-data; name=\"" + entry.getkey() + "\"" + linend);
      sb.append("content-type: text/plain; charset=" + charset + linend);
      sb.append("content-transfer-encoding: 8bit" + linend);
      sb.append(linend);
      sb.append(entry.getvalue());
      sb.append(linend);
    }

    dataoutputstream outstream = new dataoutputstream(conn.getoutputstream());
    outstream.write(sb.tostring().getbytes());
    inputstream in = null;
    // 发送文件数据
    if (files != null)
    {
      for (map.entry<string, file> file : files.entryset())
      {
        stringbuilder sb1 = new stringbuilder();
        sb1.append(prefix);
        sb1.append(boundary);
        sb1.append(linend);
        // name是post中传参的键 filename是文件的名称
        sb1.append("content-disposition: form-data; name=\"file\"; filename=\"" + file.getkey() + "\"" + linend);
        sb1.append("content-type: application/octet-stream; charset=" + charset + linend);
        sb1.append(linend);
        outstream.write(sb1.tostring().getbytes());

        inputstream is = new fileinputstream(file.getvalue());
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = is.read(buffer)) != -1)
        {
          outstream.write(buffer, 0, len);
        }

        is.close();
        outstream.write(linend.getbytes());
      }

      // 请求结束标志
      byte[] end_data = (prefix + boundary + prefix + linend).getbytes();
      outstream.write(end_data);
      outstream.flush();
      // 得到响应码
      int res = conn.getresponsecode();
      if (res == 200)
      {
        in = conn.getinputstream();
        int ch;
        stringbuilder sb2 = new stringbuilder();
        while ((ch = in.read()) != -1)
        {
          sb2.append((char) ch);
        }
      }
      outstream.close();
      conn.disconnect();
    }
    // return in.tostring();
  }

以数据流的形式传参

public static string postfile(string actionurl, map<string, string> params, map<string, byte[]> files)
      throws exception
  {
    stringbuilder sb2 = null;
    string boundary = java.util.uuid.randomuuid().tostring();
    string prefix = "--", linend = "\r\n";
    string multipart_from_data = "multipart/form-data";
    string charset = "utf-8";

    url uri = new url(actionurl);
    httpurlconnection conn = (httpurlconnection) uri.openconnection();
    conn.setreadtimeout(6 * 1000); // 缓存的最长时间
    conn.setdoinput(true);// 允许输入
    conn.setdooutput(true);// 允许输出
    conn.setusecaches(false); // 不允许使用缓存
    conn.setrequestmethod("post");
    conn.setrequestproperty("connection", "keep-alive");
    conn.setrequestproperty("charsert", "utf-8");
    conn.setrequestproperty("content-type", multipart_from_data + ";boundary=" + boundary);

    // 首先组拼文本类型的参数
    stringbuilder sb = new stringbuilder();
    for (map.entry<string, string> entry : params.entryset())
    {
      sb.append(prefix);
      sb.append(boundary);
      sb.append(linend);
      sb.append("content-disposition: form-data; name=\"" + entry.getkey() + "\"" + linend);
      sb.append("content-type: text/plain; charset=" + charset + linend);
      sb.append("content-transfer-encoding: 8bit" + linend);
      sb.append(linend);
      sb.append(entry.getvalue());
      sb.append(linend);
    }

    dataoutputstream outstream = new dataoutputstream(conn.getoutputstream());
    outstream.write(sb.tostring().getbytes());
    inputstream in = null;
    // 发送文件数据
    if (files != null)
    {
      for (map.entry<string, byte[]> file : files.entryset())
      {
        stringbuilder sb1 = new stringbuilder();
        sb1.append(prefix);
        sb1.append(boundary);
        sb1.append(linend);
        sb1.append("content-disposition: form-data; name=\"pic\"; filename=\"" + file.getkey() + "\"" + linend);
        sb1.append("content-type: application/octet-stream; charset=" + charset + linend);
        sb1.append(linend);
        outstream.write(sb1.tostring().getbytes());

        // inputstream is = new fileinputstream(file.getvalue());
        // byte[] buffer = new byte[1024];
        // int len = 0;
        // while ((len = is.read(buffer)) != -1)
        // {
        // outstream.write(buffer, 0, len);
        // }
        // is.close();
        outstream.write(file.getvalue());

        outstream.write(linend.getbytes());
      }

      // 请求结束标志
      byte[] end_data = (prefix + boundary + prefix + linend).getbytes();
      outstream.write(end_data);
      outstream.flush();
      // 得到响应码
      int res = conn.getresponsecode();
      if (res == 200)
      {
        in = conn.getinputstream();
        int ch;
        sb2 = new stringbuilder();
        while ((ch = in.read()) != -1)
        {
          sb2.append((char) ch);
        }
        system.out.println(sb2.tostring());
      }
      outstream.close();
      conn.disconnect();
      // 解析服务器返回来的数据
      return parsejson.geteditmadiconresult(sb2.tostring());
    }
    else
    {
      return "update icon fail";
    }
    // return in.tostring();
  }

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

上一篇:

下一篇: