• Java技能树-网络-HTTP-HttpURLConnection


    1 需求

    • 需求1:发送GET请求
    • 需求2:发送POST请求
    • 需求3:上传文件
    • 需求4:同时上传文件和参数

    2 接口

    Class HttpURLConnection


    java.lang.Object 
            java.net.URLConnection 
                    java.net.HttpURLConnection 

    public abstract class HttpURLConnection extends URLConnection

    Field Detail

    Constructor Detail

    • protected HttpURLConnection(URL u)


    Method Detail

    • public void setRequestMethod(String method) throws ProtocolException
    • public int getResponseCode() throws IOException

    Class URLConnection


    java.lang.Object 
            java.net.URLConnection


    public abstract class URLConnection extends Object

    Field Detail

    Constructor Detail

    Method Detail

    • public InputStream getInputStream() throws IOException
       

    Class URL


    java.lang.Object 
            java.net.URL


    public final class URL extends Object implements Serializable

    Constructor Detail

    • public URL(String spec) throws MalformedURLException

    Method Detail

    • public URLConnection openConnection() throws IOException
    • public URLConnection openConnection(Proxy proxy) throws IOException

    3 示例

    1. import java.io.BufferedReader;
    2. import java.io.IOException;
    3. import java.io.InputStream;
    4. import java.io.InputStreamReader;
    5. import java.net.HttpURLConnection;
    6. import java.net.URL;
    7. /**
    8. * 第一步,创建远程连接
    9. * 第二步,设置连接方式(get、post、put。。。)
    10. * 第三步,设置连接超时时间
    11. * 第四步,设置响应读取时间
    12. * 第五步,发起请求
    13. * 第六步,获取请求数据
    14. * 第七步,关闭连接
    15. */
    16. public class Test {
    17. public static void main(String[] args) {
    18. StringBuffer result = new StringBuffer();
    19. try {
    20. // 创建连接
    21. URL url = new URL("http://www.dvwa.com/login.php");
    22. HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    23. // 设置请求方式
    24. connection.setRequestMethod("GET");
    25. // 设置连接超时时间
    26. connection.setReadTimeout(15000);
    27. // 开始连接
    28. connection.connect();
    29. // 获取请求数据
    30. if (connection.getResponseCode() == 200) {
    31. InputStream is = connection.getInputStream();
    32. if (is != null) {
    33. InputStreamReader ir = new InputStreamReader(is, "UTF-8");
    34. BufferedReader br = new BufferedReader(ir);
    35. String line = null;
    36. while ((line = br.readLine()) != null) {
    37. result.append(line);
    38. }
    39. }
    40. }
    41. //
    42. connection.disconnect();
    43. } catch (IOException e) {
    44. e.printStackTrace();
    45. }
    46. System.out.println(result);
    47. }
    48. }

    3.X 需求:文件上传

    1. import java.io.BufferedInputStream;
    2. import java.io.BufferedReader;
    3. import java.io.DataOutputStream;
    4. import java.io.File;
    5. import java.io.FileInputStream;
    6. import java.io.FileOutputStream;
    7. import java.io.IOException;
    8. import java.io.InputStream;
    9. import java.io.InputStreamReader;
    10. import java.io.OutputStream;
    11. import java.io.OutputStreamWriter;
    12. import java.net.HttpURLConnection;
    13. import java.net.MalformedURLException;
    14. import java.net.URL;
    15. import java.net.URLConnection;
    16. import java.util.Iterator;
    17. import java.util.Map;
    18. /**
    19. * Java原生的API可用于发送HTTP请求,即java.net.URL、java.net.URLConnection,这些API很好用、很常用,
    20. * 但不够简便;
    21. *
    22. * 1.通过统一资源定位器(java.net.URL)获取连接器(java.net.URLConnection) 2.设置请求的参数 3.发送请求
    23. * 4.以输入流的形式获取返回内容 5.关闭输入流
    24. *
    25. * @author H__D
    26. *
    27. */
    28. public class Test {
    29. /**
    30. * 多文件上传的方法
    31. *
    32. * @param actionUrl:上传的路径
    33. * @param uploadFilePaths:需要上传的文件路径,数组
    34. * @return
    35. */
    36. @SuppressWarnings("finally")
    37. public static String uploadFile(String actionUrl, String[] uploadFilePaths) {
    38. String end = "\r\n";
    39. String twoHyphens = "--";
    40. String boundary = "*****";
    41. DataOutputStream ds = null;
    42. InputStream inputStream = null;
    43. InputStreamReader inputStreamReader = null;
    44. BufferedReader reader = null;
    45. StringBuffer resultBuffer = new StringBuffer();
    46. String tempLine = null;
    47. try {
    48. // 统一资源
    49. URL url = new URL(actionUrl);
    50. // 连接类的父类,抽象类
    51. URLConnection urlConnection = url.openConnection();
    52. // http的连接类
    53. HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
    54. // 设置是否从httpUrlConnection读入,默认情况下是true;
    55. httpURLConnection.setDoInput(true);
    56. // 设置是否向httpUrlConnection输出
    57. httpURLConnection.setDoOutput(true);
    58. // Post 请求不能使用缓存
    59. httpURLConnection.setUseCaches(false);
    60. // 设定请求的方法,默认是GET
    61. httpURLConnection.setRequestMethod("POST");
    62. // 设置字符编码连接参数
    63. httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
    64. // 设置字符编码
    65. httpURLConnection.setRequestProperty("Charset", "UTF-8");
    66. // 设置请求内容类型
    67. httpURLConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
    68. // 设置DataOutputStream
    69. ds = new DataOutputStream(httpURLConnection.getOutputStream());
    70. for (int i = 0; i < uploadFilePaths.length; i++) {
    71. String uploadFile = uploadFilePaths[i];
    72. String filename = uploadFile.substring(uploadFile.lastIndexOf("//") + 1);
    73. ds.writeBytes(twoHyphens + boundary + end);
    74. ds.writeBytes("Content-Disposition: form-data; " + "name=\"file" + i + "\";filename=\"" + filename
    75. + "\"" + end);
    76. ds.writeBytes(end);
    77. FileInputStream fStream = new FileInputStream(uploadFile);
    78. int bufferSize = 1024;
    79. byte[] buffer = new byte[bufferSize];
    80. int length = -1;
    81. while ((length = fStream.read(buffer)) != -1) {
    82. ds.write(buffer, 0, length);
    83. }
    84. ds.writeBytes(end);
    85. /* close streams */
    86. fStream.close();
    87. }
    88. ds.writeBytes(twoHyphens + boundary + twoHyphens + end);
    89. /* close streams */
    90. ds.flush();
    91. if (httpURLConnection.getResponseCode() >= 300) {
    92. throw new Exception(
    93. "HTTP Request is not success, Response code is " + httpURLConnection.getResponseCode());
    94. }
    95. if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
    96. inputStream = httpURLConnection.getInputStream();
    97. inputStreamReader = new InputStreamReader(inputStream);
    98. reader = new BufferedReader(inputStreamReader);
    99. tempLine = null;
    100. resultBuffer = new StringBuffer();
    101. while ((tempLine = reader.readLine()) != null) {
    102. resultBuffer.append(tempLine);
    103. resultBuffer.append("\n");
    104. }
    105. }
    106. } catch (Exception e) {
    107. // TODO Auto-generated catch block
    108. e.printStackTrace();
    109. } finally {
    110. if (ds != null) {
    111. try {
    112. ds.close();
    113. } catch (IOException e) {
    114. // TODO Auto-generated catch block
    115. e.printStackTrace();
    116. }
    117. }
    118. if (reader != null) {
    119. try {
    120. reader.close();
    121. } catch (IOException e) {
    122. // TODO Auto-generated catch block
    123. e.printStackTrace();
    124. }
    125. }
    126. if (inputStreamReader != null) {
    127. try {
    128. inputStreamReader.close();
    129. } catch (IOException e) {
    130. // TODO Auto-generated catch block
    131. e.printStackTrace();
    132. }
    133. }
    134. if (inputStream != null) {
    135. try {
    136. inputStream.close();
    137. } catch (IOException e) {
    138. // TODO Auto-generated catch block
    139. e.printStackTrace();
    140. }
    141. }
    142. return resultBuffer.toString();
    143. }
    144. }
    145. public static void main(String[] args) {
    146. // 上传文件测试
    147. String str = uploadFile("http://localhost/MDM/upload.php",new String[] { "C:\\1.png" });
    148. System.out.println(str);
    149. }
    150. }

    参考资料:

    通过HttpURLConnection 上传文件_pois的博客-CSDN博客_httpurlconnection 文件上传 

    HttpUrlConnection上传文件_三木神奇的博客-CSDN博客_httpurlconnection 文件上传


    4 参考资料

    java实现调用http请求的几种常见方式_qq_duhai的博客-CSDN博客_java http

    HttpUrlConnection上传文件_三木神奇的博客-CSDN博客_httpurlconnection 文件上传

    通过HttpURLConnection 上传文件_pois的博客-CSDN博客_httpurlconnection 文件上传

  • 相关阅读:
    .NET Interop 互操作 COM+
    Opus 1.4 编译脚本
    软件安全开发生命周期(SSDL)全景图
    【Linux 从基础到进阶】自动化部署工具(Jenkins、GitLab CI/CD)
    极兔赴港:一家生而全球化的快递公司
    CPS攻击案例(一)——基于脉冲宽度调制PWM的无人机攻击
    Python zip函数及用法
    常用DOS命令
    【前端修炼场】— 列表有什么难的?
    C高级 DAY4
  • 原文地址:https://blog.csdn.net/pwp032984/article/details/127571517