服务器之家

服务器之家 > 正文

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

时间:2020-11-10 16:45     来源/作者:阿文丶

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
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请求上传文件功能实例,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对服务器之家网站的支持!

原文链接:http://blog.csdn.net/xiaose_307/article/details/72887285

相关文章

热门资讯

2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全 2019-12-26
Intellij idea2020永久破解,亲测可用!!!
Intellij idea2020永久破解,亲测可用!!! 2020-07-29
歪歪漫画vip账号共享2020_yy漫画免费账号密码共享
歪歪漫画vip账号共享2020_yy漫画免费账号密码共享 2020-04-07
电视剧《琉璃》全集在线观看 琉璃美人煞1-59集免费观看地址
电视剧《琉璃》全集在线观看 琉璃美人煞1-59集免费观看地址 2020-08-12
最新idea2020注册码永久激活(激活到2100年)
最新idea2020注册码永久激活(激活到2100年) 2020-07-29
返回顶部