Java 发送http请求上传文件功能实例

废话不多说了,直接给大家贴代码了,具体代码如下所示:

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<String, String> 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<String, String> 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<String, String> requestHeader, Map<String, String> formTexts, Map<String, String> 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<String, String> 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<String, String> 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<String, String> 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<String, String> 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<String, String> 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请求上传文件功能实例,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对我们网站的支持!

(0)

相关推荐

  • java发送http请求并获取状态码的简单实例

    目前做项目中有一个需求是这样的,需要通过java发送url请求,查看该url是否有效,这时我们可以通过获取状态码来判断. try { URL u = new URL("http://10.1.2.8:8080/fqz/page/qizha/pros_add.jsp"); try { HttpURLConnection uConnection = (HttpURLConnection) u.openConnection(); try { uConnection.connect(); Sy

  • java实现http请求工具类示例

    通过http rest请求返回数据 复制代码 代码如下: import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;import org.apache.http.NameValuePair;import org.apache.http.client.ClientProtocolException;import org.apache.http.client.HttpClient;import

  • java实现http的Post、Get、代理访问请求

    本文实例讲解了java实现http的Post.Get.代理访问请求的详细代码片段,分享给大家供大家参考,具体内容如下 package com.snowfigure.kits.net; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; im

  • java获取http请求的Header和Body的简单方法

    在http请求中,有Header和Body之分,读取header使用request.getHeader("..."); 读取Body使用request.getReader(),但getReader获取的是BufferedReader,需要把它转换成字符串,下面是转换的方法. public class TestController { @RequestMapping("/a") protected void doPost(HttpServletRequest requ

  • java使用httpclient模拟post请求和get请求示例

    复制代码 代码如下: import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader; import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;import org.apache.commons.httpclient.Header;import org

  • java模拟http的Get/Post请求,并设置ip与port代理的方法

    本文涉及3个基本点: 1.因为很多公司的内网都设有代理,浏览器通过ip与port上网,而java代码模拟http get方式同样需要外网代理: 2.Java实现http的Get/Post请求代码: 3.主要是设置HttpURLConnection请求头里面的属性 比如Cookie.User-Agent(浏览器类型)等等. 比如:http请求中添加Header conn.setRequestProperty("Authorization", authorization); 注:我就在网上

  • java发送http的get、post请求实现代码

    Http请求类 package wzh.Http; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.URL; import java.net.URLConnection; import java.util.List; import java.util.Map; public

  • java发送http get请求的两种方法(总结)

    长话短说,废话不说 一.第一种方式,通过HttpClient方式,代码如下: public static String httpGet(String url, String charset) throws HttpException, IOException { String json = null; HttpGet httpGet = new HttpGet(); // 设置参数 try { httpGet.setURI(new URI(url)); } catch (URISyntaxExc

  • JAVA发送HTTP请求,返回HTTP响应内容,应用及实例代码

    JDK 中提供了一些对无状态协议请求(HTTP )的支持,下面我就将我所写的一个小例子(组件)进行描述:首先让我们先构建一个请求类(HttpRequester ).该类封装了 JAVA 实现简单请求的代码,如下: 复制代码 代码如下: import java.io.BufferedReader;  import java.io.IOException;  import java.io.InputStream;  import java.io.InputStreamReader;  import

  • java读取http请求中的body实例代码

    在http请求中,有Header和Body之分,读取header使用request.getHeader("..."); 读取Body使用request.getReader(),但getReader获取的是BufferedReader,需要把它转换成字符串, 下面是转换的方法. public static String getBodyString(BufferedReader br) { String inputLine; String str = ""; try {

  • java遍历http请求request的所有参数实现方法

    通过程序遍历http请求的所有参数放到hashmap中,用的时候方便了. 如果参数值有中文,那么需要在程序中添加filter转码,或者在下面程序里,对paramValue转码 如下所示: public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Map map = new HashMap(); Enumeration para

  • JAVA获取HTTP请求头的方法示例

    本文实例讲述了JAVA获取HTTP请求头的方法.分享给大家供大家参考,具体如下: 在利用Java网络编程时,利用Java获取HTTP Request 和 Response头字段: 可以利用Java语言根据需要添加自定义的HTTP头字段,而不必拘泥于标准HTTP定义的头字段. 代码如下: public class TestURL { public static void main(String[] args) { String destURLStr= "http://www.baidu.com&q

随机推荐