当前位置: 移动技术网 > IT编程>开发语言>Java > Java 中HttpURLConnection附件上传的实例详解

Java 中HttpURLConnection附件上传的实例详解

2019年07月19日  | 移动技术网IT编程  | 我要评论

java 中httpurlconnection附件上传的实例详解

整合了一个自己写的采用http做附件上传的工具,分享一下!

示例代码:

/** 
 * 以http协议传输文件 
 * 
 * @author mingxue.zhang@163.com 
 * 
 */ 
public class httppostutil { 
 
  private final static char[] multipart_chars = "-_1234567890abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz" 
      .tochararray(); 
 
  private url url; 
  private httpurlconnection conn; 
  private string boundary = null; 
  private map<string, string> textparams = new hashmap<string, string>(); 
  private map<string, file> fileparams = new hashmap<string, file>(); 
 
  public httppostutil(string url) throws exception { 
    this.url = new url(url); 
  } 
 
  // 重新设置要请求的服务器地址,即上传文件的地址。 
  public void seturl(string url) throws exception { 
    this.url = new url(url); 
  } 
 
  // 增加一个普通字符串数据到form表单数据中 
  public void addtextparameter(string name, string value) { 
    textparams.put(name, value); 
  } 
 
  // 增加一个文件到form表单数据中 
  public void addfileparameter(string name, file value) { 
    fileparams.put(name, value); 
  } 
 
  // 清空所有已添加的form表单数据 
  public void clearallparameters() { 
    textparams.clear(); 
    fileparams.clear(); 
  } 
 
  /** 
   * 发送数据到服务器 
   * 
   * @return 一个字节包含服务器的返回结果的数组 
   * @throws exception 
   */ 
  public byte[] send() throws exception { 
    initconnection(); 
    try { 
      conn.connect(); 
    } catch (sockettimeoutexception e) { 
      throw new exception(e); 
    } 
 
    outputstream connoutstream = new dataoutputstream( 
        conn.getoutputstream()); 
 
    writefileparams(connoutstream); 
    writestringparams(connoutstream); 
    writesend(connoutstream); 
 
    inputstream responseinstream = conn.getinputstream(); 
    bytearrayoutputstream responseoutstream = new bytearrayoutputstream(); 
    int len; 
    byte[] bufferbyte = new byte[1024]; 
    while ((len = responseinstream.read(bufferbyte)) != -1) { 
      responseoutstream.write(bufferbyte, 0, len); 
    } 
    responseinstream.close(); 
    connoutstream.close(); 
 
    conn.disconnect(); 
    byte[] resultbyte = responseoutstream.tobytearray(); 
    responseoutstream.close(); 
    return resultbyte; 
  } 
 
  // 文件上传的connection的一些必须设置 
  private void initconnection() throws exception { 
    stringbuffer buf = new stringbuffer("----"); 
    random rand = new random(); 
    for (int i = 0; i < 15; i++) { 
      buf.append(multipart_chars[rand.nextint(multipart_chars.length)]); 
    } 
    this.boundary = buf.tostring(); 
 
    conn = (httpurlconnection) this.url.openconnection(); 
    conn.setdooutput(true); 
    conn.setusecaches(false); 
    conn.setconnecttimeout(3 * 60 * 1000); // 连接超时为10秒 
    conn.setrequestmethod("post"); 
    conn.setrequestproperty("content-type", 
        "multipart/form-data; boundary=" + boundary); 
  } 
 
  // 普通字符串数据 
  private void writestringparams(outputstream out) throws exception { 
    set<string> keyset = textparams.keyset(); 
    for (iterator<string> it = keyset.iterator(); it.hasnext();) { 
      string name = it.next(); 
      string value = textparams.get(name); 
 
      out.write(("--" + boundary + "\r\n").getbytes()); 
      out.write(("content-disposition: form-data; name=\"" + name + "\"\r\n") 
          .getbytes()); 
      out.write(("\r\n").getbytes()); 
      out.write((encode(value) + "\r\n").getbytes()); 
    } 
  } 
 
  // 文件数据 
  private void writefileparams(outputstream out) throws exception { 
    set<string> keyset = fileparams.keyset(); 
    for (iterator<string> it = keyset.iterator(); it.hasnext();) { 
      string name = it.next(); 
      file value = fileparams.get(name); 
 
      out.write(("--" + boundary + "\r\n").getbytes()); 
      out.write(("content-disposition: form-data; name=\"" + name 
          + "\"; filename=\"" + encode(value.getname()) + "\"\r\n") 
          .getbytes()); 
      out.write(("content-type: " + getcontenttype(value) + "\r\n") 
          .getbytes()); 
      out.write(("content-transfer-encoding: " + "binary" + "\r\n") 
          .getbytes()); 
 
      out.write(("\r\n").getbytes()); 
 
      fileinputstream instream = new fileinputstream(value); 
      int bytes = 0; 
      byte[] bufferbyte = new byte[1024]; 
      while ((bytes = instream.read(bufferbyte)) != -1) { 
        out.write(bufferbyte, 0, bytes); 
      } 
      instream.close(); 
 
      out.write(("\r\n").getbytes()); 
    } 
  } 
 
  // 添加结尾数据 
  private void writesend(outputstream out) throws exception { 
    out.write(("--" + boundary + "--" + "\r\n").getbytes()); 
    out.write(("\r\n").getbytes()); 
  } 
 
  // 获取文件的上传类型,图片格式为image/png,image/jpg等。非图片为application/octet-stream 
  private string getcontenttype(file f) throws exception { 
    string filename = f.getname(); 
    if (filename.endswith(".jpg")) { 
      return "image/jpeg"; 
    } else if (filename.endswith(".png")) { 
      return "image/png"; 
    } 
    return "application/octet-stream"; 
  } 
 
  // 对包含中文的字符串进行转码,此为utf-8。服务器那边要进行一次解码 
  private string encode(string value) throws exception { 
    return urlencoder.encode(value, "utf-8"); 
  } 
 
} 

如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网