在Java项目中如果发送http请求实现文件上传功能

在Java项目中如果发送http请求实现文件上传功能?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。

创新互联坚信:善待客户,将会成为终身客户。我们能坚持多年,是因为我们一直可值得信赖。我们从不忽悠初访客户,我们用心做好本职工作,不忘初心,方得始终。10余年网站建设经验创新互联是成都老牌网站营销服务商,为您提供成都网站设计、网站制作、网站设计、H5开发、网站制作、成都品牌网站建设微信小程序服务,给众多知名企业提供过好品质的建站服务。

具体代码如下所示:

package wxapi.WxHelper; 
import java.io.BufferedReader; 
import java.io.DataInputStream; 
import java.io.DataOutputStream; 
import java.io.File; 
import java.io.FileInputStream; 
import java.io.IOException; 
import java.io.InputStreamReader; 
import java.io.OutputStream; 
import java.net.HttpURLConnection; 
import java.net.URL; 
import java.net.URLConnection; 
import java.util.Date; 
import java.util.Map; 
import java.util.Map.Entry; 
public class HttpRequestUtil { 
  /** 
   * 发送get请求 
   * 
   * @param requestUrl 
   *      请求url 
   * @param requestHeader 
   *      请求头 
   * @param responseEncoding 
   *      响应编码 
   * @return 页面响应html 
   */ 
  public static String sendGet(String requestUrl, Map requestHeader, String responseEncoding) { 
    String result = ""; 
    BufferedReader reader = null; 
    try { 
      if (requestUrl == null || requestUrl.isEmpty()) { 
        return result; 
      } 
      URL realUrl = new URL(requestUrl); 
      URLConnection connection = realUrl.openConnection(); 
      connection.setRequestProperty("accept", "text/html, application/xhtml+xml, image/jxr, */*"); 
      connection.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:53.0) Gecko/20100101 Firefox/53.0"); 
      if (requestHeader != null && requestHeader.size() > 0) { 
        for (Entry entry : requestHeader.entrySet()) { 
          connection.setRequestProperty(entry.getKey(), entry.getValue()); 
        } 
      } 
      connection.connect(); 
      if (responseEncoding == null || responseEncoding.isEmpty()) { 
        responseEncoding = "UTF-8"; 
      } 
      reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), responseEncoding)); 
      String line; 
      while ((line = reader.readLine()) != null) { 
        result += line; 
      } 
    } catch (Exception e) { 
      System.out.println("发送GET请求出现异常!"); 
      e.printStackTrace(); 
    } finally { 
      try { 
        if (reader != null) { 
          reader.close(); 
        } 
      } catch (Exception e) { 
        e.printStackTrace(); 
      } 
    } 
    return result; 
  } 
  /** 
   * 发送post请求 
   *  
   * @param requestUrl 
   *      请求url 
   * @param requestHeader 
   *      请求头 
   * @param formTexts 
   *      表单数据 
   * @param files 
   *      上传文件 
   * @param requestEncoding 
   *      请求编码 
   * @param responseEncoding 
   *      响应编码 
   * @return 页面响应html 
   */ 
  public static String sendPost(String requestUrl, Map requestHeader, Map formTexts, Map files, String requestEncoding, String responseEncoding) { 
    OutputStream out = null; 
    BufferedReader reader = null; 
    String result = ""; 
    try { 
      if (requestUrl == null || requestUrl.isEmpty()) { 
        return result; 
      } 
      URL realUrl = new URL(requestUrl); 
      HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection(); 
      connection.setRequestProperty("accept", "text/html, application/xhtml+xml, image/jxr, */*"); 
      connection.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:53.0) Gecko/20100101 Firefox/53.0"); 
      if (requestHeader != null && requestHeader.size() > 0) { 
        for (Entry entry : requestHeader.entrySet()) { 
          connection.setRequestProperty(entry.getKey(), entry.getValue()); 
        } 
      } 
      connection.setDoOutput(true); 
      connection.setDoInput(true); 
      connection.setRequestMethod("POST"); 
      if (requestEncoding == null || requestEncoding.isEmpty()) { 
        requestEncoding = "UTF-8"; 
      } 
      if (responseEncoding == null || responseEncoding.isEmpty()) { 
        responseEncoding = "UTF-8"; 
      } 
      if (requestHeader != null && requestHeader.size() > 0) { 
        for (Entry entry : requestHeader.entrySet()) { 
          connection.setRequestProperty(entry.getKey(), entry.getValue()); 
        } 
      } 
      if (files == null || files.size() == 0) { 
        connection.setRequestProperty("content-type", "application/x-www-form-urlencoded"); 
        out = new DataOutputStream(connection.getOutputStream()); 
        if (formTexts != null && formTexts.size() > 0) { 
          String formData = ""; 
          for (Entry entry : formTexts.entrySet()) { 
            formData += entry.getKey() + "=" + entry.getValue() + "&"; 
          } 
          formData = formData.substring(0, formData.length() - 1); 
          out.write(formData.toString().getBytes(requestEncoding)); 
        } 
      } else { 
        String boundary = "-----------------------------" + String.valueOf(new Date().getTime()); 
        connection.setRequestProperty("content-type", "multipart/form-data; boundary=" + boundary); 
        out = new DataOutputStream(connection.getOutputStream()); 
        if (formTexts != null && formTexts.size() > 0) { 
          StringBuilder sbFormData = new StringBuilder(); 
          for (Entry entry : formTexts.entrySet()) { 
            sbFormData.append("--" + boundary + "\r\n"); 
            sbFormData.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"\r\n\r\n"); 
            sbFormData.append(entry.getValue() + "\r\n"); 
          } 
          out.write(sbFormData.toString().getBytes(requestEncoding)); 
        } 
        for (Entry entry : files.entrySet()) { 
          String fileName = entry.getKey(); 
          String filePath = entry.getValue(); 
          if (fileName == null || fileName.isEmpty() || filePath == null || filePath.isEmpty()) { 
            continue; 
          } 
          File file = new File(filePath); 
          if (!file.exists()) { 
            continue; 
          } 
          out.write(("--" + boundary + "\r\n").getBytes(requestEncoding)); 
          out.write(("Content-Disposition: form-data; name=\"" + fileName + "\"; filename=\"" + file.getName() + "\"\r\n").getBytes(requestEncoding)); 
          out.write(("Content-Type: application/x-msdownload\r\n\r\n").getBytes(requestEncoding)); 
          DataInputStream in = new DataInputStream(new FileInputStream(file)); 
          int bytes = 0; 
          byte[] bufferOut = new byte[1024]; 
          while ((bytes = in.read(bufferOut)) != -1) { 
            out.write(bufferOut, 0, bytes); 
          } 
          in.close(); 
          out.write(("\r\n").getBytes(requestEncoding)); 
        } 
        out.write(("--" + boundary + "--").getBytes(requestEncoding)); 
      } 
      out.flush(); 
      out.close(); 
      out = null; 
      reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), responseEncoding)); 
      String line; 
      while ((line = reader.readLine()) != null) { 
        result += line; 
      } 
    } catch (Exception e) { 
      System.out.println("发送POST请求出现异常!"); 
      e.printStackTrace(); 
    } finally { 
      try { 
        if (out != null) { 
          out.close(); 
        } 
        if (reader != null) { 
          reader.close(); 
        } 
      } catch (IOException ex) { 
        ex.printStackTrace(); 
      } 
    } 
    return result; 
  } 
} 

看完上述内容,你们掌握在Java项目中如果发送http请求实现文件上传功能的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注创新互联行业资讯频道,感谢各位的阅读!


文章题目:在Java项目中如果发送http请求实现文件上传功能
文章路径:http://scyanting.com/article/ppdohp.html