HttpURLConnection实现HttpClient工具类(get/post请求,文件上传)

一时失言乱红尘 2022-06-04 00:08 273阅读 0赞

本博客简单介绍一下HttpURLConnection实现的POST和GET请求以及文件上传,还有文件上传的服务器代码实现。

  1. import java.io.BufferedReader;
  2. import java.io.DataOutputStream;
  3. import java.io.File;
  4. import java.io.FileInputStream;
  5. import java.io.InputStream;
  6. import java.io.InputStreamReader;
  7. import java.io.OutputStream;
  8. import java.net.HttpURLConnection;
  9. import java.net.URL;
  10. import java.net.URLEncoder;
  11. import java.util.HashMap;
  12. import java.util.Map;
  13. import org.apache.http.client.HttpResponseException;
  14. import org.slf4j.Logger;
  15. import org.slf4j.LoggerFactory;
  16. public class HttpClient {
  17. protected final static Logger logger = LoggerFactory.getLogger(HttpClient.class);
  18. /**
  19. * Description:文件上传,以及可以传递参数,支持文件批量上传
  20. *
  21. * @param actionUrl 请求地址
  22. * @param params 参数
  23. * @param files 多个文件
  24. * @return
  25. * @throws Exception
  26. */
  27. public static Map<String, Object> post(String actionUrl, Map<String, String> params, Map<String, File> files)
  28. throws Exception {
  29. Map<String, Object> map = new HashMap<String, Object>();
  30. logger.info("post file url:" + actionUrl + " params:" + params);
  31. String BOUNDARY = java.util.UUID.randomUUID().toString();
  32. String PREFIX = "--", LINEND = "\r\n";
  33. String MULTIPART_FROM_DATA = "multipart/form-data";
  34. String CHARSET = "UTF-8";
  35. URL uri = new URL(actionUrl);
  36. HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
  37. conn.setReadTimeout(10 * 1000); // cache max time
  38. conn.setConnectTimeout(5*1000);
  39. conn.setDoInput(true);// allow input
  40. conn.setDoOutput(true);// allow output
  41. conn.setUseCaches(false); // cache is disable
  42. conn.setRequestMethod("POST");
  43. conn.setRequestProperty("connection", "keep-alive");
  44. conn.setRequestProperty("Charsert", "UTF-8");
  45. conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA + ";boundary=" + BOUNDARY);
  46. // construct params for Text
  47. StringBuilder sb = new StringBuilder();
  48. for (Map.Entry<String, String> entry : params.entrySet()) {
  49. sb.append(PREFIX);
  50. sb.append(BOUNDARY);
  51. sb.append(LINEND);
  52. sb.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"" + LINEND);
  53. sb.append("Content-Type: text/plain; charset=" + CHARSET + LINEND);
  54. sb.append("Content-Transfer-Encoding: 8bit" + LINEND);
  55. sb.append(LINEND);
  56. sb.append(entry.getValue());
  57. sb.append(LINEND);
  58. }
  59. DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());
  60. outStream.write(sb.toString().getBytes("utf-8"));
  61. // send data
  62. if (files != null) {
  63. for (Map.Entry<String, File> file : files.entrySet()) {
  64. StringBuilder sb1 = new StringBuilder();
  65. sb1.append(PREFIX);
  66. sb1.append(BOUNDARY);
  67. sb1.append(LINEND);
  68. sb1.append("Content-Disposition: form-data; name=\"" + file.getKey() + "\"; filename=\""
  69. + file.getValue() + "\"" + LINEND);
  70. sb1.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINEND);
  71. sb1.append(LINEND);
  72. outStream.write(sb1.toString().getBytes());
  73. InputStream is = new FileInputStream(file.getValue());
  74. try {
  75. byte[] buffer = new byte[(int) file.getValue().length()];
  76. int len = 0;
  77. while ((len = is.read(buffer)) != -1) {
  78. outStream.write(buffer, 0, len);
  79. }
  80. } catch (Exception e) {
  81. throw e;
  82. } finally {
  83. is.close();
  84. outStream.write(LINEND.getBytes());
  85. }
  86. }
  87. }
  88. // the finsh flag
  89. byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
  90. outStream.write(end_data);
  91. outStream.flush();
  92. // get response
  93. int res = conn.getResponseCode();
  94. map.put("status", res);
  95. InputStream in = null;
  96. String result = null;
  97. switch (res) {
  98. case 200:
  99. in = conn.getInputStream();
  100. int ch;
  101. StringBuilder sb2 = new StringBuilder();
  102. while ((ch = in.read()) != -1) {
  103. sb2.append((char) ch);
  104. }
  105. result = sb2.toString();
  106. map.put("returnString", result);
  107. break;
  108. case 403:
  109. throw new HttpResponseException(res, "request forbided");
  110. case 404:
  111. throw new HttpResponseException(res, "not fonud such address");
  112. default:
  113. throw new Exception("undefine error:" + res);
  114. }
  115. conn.disconnect();
  116. return map;
  117. }
  118. public static String post(String actionUrl, Map<String, String> params) throws Exception {
  119. String contentType = "application/x-www-form-urlencoded";
  120. URL uri = new URL(actionUrl);
  121. HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
  122. conn.setReadTimeout(5 * 1000); // Cache max time
  123. conn.setConnectTimeout(5*1000);
  124. conn.setDoInput(true);// allow input
  125. conn.setDoOutput(true);// Allow output
  126. conn.setUseCaches(false); // cache is disable
  127. conn.setRequestMethod("POST");
  128. conn.setRequestProperty("connection", "keep-alive");
  129. conn.setRequestProperty("Charsert", "UTF-8");
  130. conn.setRequestProperty("Content-Type", contentType);
  131. StringBuilder sb = new StringBuilder();
  132. for (Map.Entry<String, String> entry : params.entrySet()) {
  133. if (sb.length() > 0) {
  134. sb.append("&");
  135. }
  136. sb.append(entry.getKey());
  137. sb.append("=");
  138. sb.append(URLEncoder.encode(entry.getValue()));
  139. }
  140. OutputStream output = conn.getOutputStream();
  141. output.write(sb.toString().getBytes());
  142. output.flush();
  143. int res = conn.getResponseCode();
  144. InputStream in = null;
  145. String result = null;
  146. switch (res) {
  147. case 200:
  148. in = conn.getInputStream();
  149. String line;
  150. StringBuilder sb2 = new StringBuilder();
  151. BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in,"UTF-8"));
  152. while ((line = bufferedReader.readLine()) != null) {
  153. sb2.append(line);
  154. }
  155. result = sb2.toString();
  156. break;
  157. case 403:
  158. throw new HttpResponseException(res, "request forbided");
  159. case 404:
  160. throw new HttpResponseException(res, "not fonud such address");
  161. default:
  162. throw new Exception("undefine error:" + res);
  163. }
  164. return result;
  165. }
  166. public static String get(String actionUrl, Map<String, String> params) throws Exception {
  167. String contentType = "application/x-www-form-urlencoded";
  168. StringBuilder sb = new StringBuilder();
  169. for (Map.Entry<String, String> entry : params.entrySet()) {
  170. if (sb.length() > 0) {
  171. sb.append("&");
  172. }
  173. sb.append(entry.getKey());
  174. sb.append("=");
  175. sb.append(URLEncoder.encode(entry.getValue()));
  176. }
  177. if (actionUrl.endsWith("?")) {
  178. actionUrl += sb.toString();
  179. } else {
  180. actionUrl += "?" + sb.toString();
  181. }
  182. URL uri = new URL(actionUrl);
  183. HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
  184. conn.setReadTimeout(5 * 1000); // Cache max time
  185. conn.setDoInput(true);// allow input
  186. conn.setDoOutput(true);// Allow output
  187. conn.setUseCaches(false); // cache is disable
  188. conn.setRequestMethod("GET");
  189. conn.setRequestProperty("connection", "keep-alive");
  190. conn.setRequestProperty("Charsert", "UTF-8");
  191. conn.setRequestProperty("Content-Type", contentType);
  192. int res = conn.getResponseCode();
  193. // Log.i("le_assistant","actionUrl:" +actionUrl+" ResponseCode:"+res);
  194. InputStream in = null;
  195. String result = null;
  196. switch (res) {
  197. case 200:
  198. in = conn.getInputStream();
  199. String line;
  200. StringBuilder sb2 = new StringBuilder();
  201. BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in,"UTF-8"));
  202. while ((line = bufferedReader.readLine()) != null) {
  203. sb2.append(line);
  204. }
  205. result = sb2.toString();
  206. break;
  207. case 403:
  208. throw new HttpResponseException(res, "request forbided");
  209. case 404:
  210. throw new HttpResponseException(res, "not fonud such address");
  211. default:
  212. throw new Exception("undefine error:" + res);
  213. }
  214. return result;
  215. }
  216. public static void main(String[] args) {
  217. String url = "http://localhost:8990/file/Upload";
  218. Map<String,String> params = new HashMap<String, String>();
  219. Map<String, File> files = new HashMap<String, File>();
  220. File file = new File("d:\\a.png");
  221. files.put("file", file);
  222. try {
  223. System.out.println(post(url, params,files));
  224. } catch (Exception e) {
  225. e.printStackTrace();
  226. }
  227. }
  228. }

文件上传的服务器代码实现(Java):

  1. @RestController
  2. @RequestMapping("/file")
  3. public class FileUploadController {
  4. /**
  5. * 图片上传
  6. * @param file
  7. * @return
  8. */
  9. @RequestMapping("/upload")
  10. @ResponseBody
  11. public Object fileUpload(@RequestParam(value = "file", required = false) MultipartFile file){
  12. JSONObject object = new JSONObject();
  13. try {
  14. if(file!=null){
  15. //保存文件
  16. String fileName = file.getOriginalFilename();
  17. String fileExt = getExtention(fileName);
  18. byte[] fileByte = file.getBytes();
  19. //文件处理
  20. }
  21. } catch (IOException e) {
  22. e.printStackTrace();
  23. }
  24. return object;
  25. }
  26. }

发表评论

表情:
评论列表 (有 0 条评论,273人围观)

还没有评论,来说两句吧...

相关阅读