Java原生的API可用于发送HTTP请求

即java.net.URL、java.net.URLConnection,JDK自带的类;

1.通过统一资源定位器(java.net.URL)获取连接器(java.net.URLConnection)

2.设置请求的参数

3.发送请求

4.以输入流的形式获取返回内容

5.关闭输入流

封装请求类

1 package com.util;

2

3 import java.io.BufferedReader;

4 import java.io.IOException;

5 import java.io.InputStream;

6 import java.io.InputStreamReader;

7 import java.io.OutputStream;

8 import java.io.OutputStreamWriter;

9 import java.net.HttpURLConnection;

10 import java.net.MalformedURLException;

11 import java.net.URL;

12 import java.net.URLConnection;

13 import java.util.Iterator;

14 import java.util.Map;

15

16 public class HttpConnectionUtil {

17

18     // post请求

19     public static final String HTTP_POST = "POST";

20

21     // get请求

22     public static final String HTTP_GET = "GET";

23

24     // utf-8字符编码

25     public static final String CHARSET_UTF_8 = "utf-8";

26

27     // HTTP内容类型。如果未指定ContentType,默认为TEXT/HTML

28     public static final String CONTENT_TYPE_TEXT_HTML = "text/xml";

29

30     // HTTP内容类型。相当于form表单的形式,提交暑假

31     public static final String CONTENT_TYPE_FORM_URL = "application/x-www-form-urlencoded";

32

33     // 请求超时时间

34     public static final int SEND_REQUEST_TIME_OUT = 50000;

35

36     // 将读超时时间

37     public static final int READ_TIME_OUT = 50000;

38

39     /**

40      *

41      * @param requestType

42      *            请求类型

43      * @param urlStr

44      *            请求地址

45      * @param body

46      *            请求发送内容

47      * @return 返回内容

48      */

49     public static String requestMethod(String requestType, String urlStr, String body) {

50

51         // 是否有http正文提交

52         boolean isDoInput = false;

53         if (body != null && body.length() > 0)

54             isDoInput = true;

55         OutputStream outputStream = null;

56         OutputStreamWriter outputStreamWriter = null;

57         InputStream inputStream = null;

58         InputStreamReader inputStreamReader = null;

59         BufferedReader reader = null;

60         StringBuffer resultBuffer = new StringBuffer();

61         String tempLine = null;

62         try {

63             // 统一资源

64             URL url = new URL(urlStr);

65             // 连接类的父类,抽象类

66             URLConnection urlConnection = url.openConnection();

67             // http的连接类

68             HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;

69

70             // 设置是否向httpUrlConnection输出,因为这个是post请求,参数要放在

71             // http正文内,因此需要设为true, 默认情况下是false;

72             if (isDoInput) {

73                 httpURLConnection.setDoOutput(true);

74                 httpURLConnection.setRequestProperty("Content-Length", String.valueOf(body.length()));

75             }

76             // 设置是否从httpUrlConnection读入,默认情况下是true;

77             httpURLConnection.setDoInput(true);

78             // 设置一个指定的超时值(以毫秒为单位)

79             httpURLConnection.setConnectTimeout(SEND_REQUEST_TIME_OUT);

80             // 将读超时设置为指定的超时,以毫秒为单位。

81             httpURLConnection.setReadTimeout(READ_TIME_OUT);

82             // Post 请求不能使用缓存

83             httpURLConnection.setUseCaches(false);

84             // 设置字符编码

85             httpURLConnection.setRequestProperty("Accept-Charset", CHARSET_UTF_8);

86             // 设置内容类型

87             httpURLConnection.setRequestProperty("Content-Type", CONTENT_TYPE_FORM_URL);

88             // 设定请求的方法,默认是GET

89             httpURLConnection.setRequestMethod(requestType);

90

91             // 打开到此 URL 引用的资源的通信链接(如果尚未建立这样的连接)。

92             // 如果在已打开连接(此时 connected 字段的值为 true)的情况下调用 connect 方法,则忽略该调用。

93             httpURLConnection.connect();

94

95             if (isDoInput) {

96                 outputStream = httpURLConnection.getOutputStream();

97                 outputStreamWriter = new OutputStreamWriter(outputStream);

98                 outputStreamWriter.write(body);

99                 outputStreamWriter.flush();// 刷新

100             }

101             if (httpURLConnection.getResponseCode() >= 300) {

102                 throw new Exception(

103                         "HTTP Request is not success, Response code is " + httpURLConnection.getResponseCode());

104             }

105

106             if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {

107                 inputStream = httpURLConnection.getInputStream();

108                 inputStreamReader = new InputStreamReader(inputStream);

109                 reader = new BufferedReader(inputStreamReader);

110

111                 while ((tempLine = reader.readLine()) != null) {

112                     resultBuffer.append(tempLine);

113                     resultBuffer.append("\n");

114                 }

115             }

116

117         } catch (MalformedURLException e) {

118             // TODO Auto-generated catch block

119             e.printStackTrace();

120         } catch (IOException e) {

121             // TODO Auto-generated catch block

122             e.printStackTrace();

123         } catch (Exception e) {

124             // TODO Auto-generated catch block

125             e.printStackTrace();

126         } finally {// 关闭流

127

128             try {

129                 if (outputStreamWriter != null) {

130                     outputStreamWriter.close();

131                 }

132             } catch (Exception e) {

133                 // TODO Auto-generated catch block

134                 e.printStackTrace();

135             }

136             try {

137                 if (outputStream != null) {

138                     outputStream.close();

139                 }

140             } catch (Exception e) {

141                 // TODO Auto-generated catch block

142                 e.printStackTrace();

143             }

144             try {

145                 if (reader != null) {

146                     reader.close();

147                 }

148             } catch (Exception e) {

149                 // TODO Auto-generated catch block

150                 e.printStackTrace();

151             }

152             try {

153                 if (inputStreamReader != null) {

154                     inputStreamReader.close();

155                 }

156             } catch (Exception e) {

157                 // TODO Auto-generated catch block

158                 e.printStackTrace();

159             }

160             try {

161                 if (inputStream != null) {

162                     inputStream.close();

163                 }

164             } catch (Exception e) {

165                 // TODO Auto-generated catch block

166                 e.printStackTrace();

167             }

168         }

169         return resultBuffer.toString();

170     }

171

172     /**

173      * 将map集合的键值对转化成:key1=value1&key2=value2 的形式

174      *

175      * @param parameterMap

176      *            需要转化的键值对集合

177      * @return 字符串

178      */

179     public static String convertStringParamter(Map parameterMap) {

180         StringBuffer parameterBuffer = new StringBuffer();

181         if (parameterMap != null) {

182             Iterator iterator = parameterMap.keySet().iterator();

183             String key = null;

184             String value = null;

185             while (iterator.hasNext()) {

186                 key = (String) iterator.next();

187                 if (parameterMap.get(key) != null) {

188                     value = (String) parameterMap.get(key);

189                 } else {

190                     value = "";

191                 }

192                 parameterBuffer.append(key).append("=").append(value);

193                 if (iterator.hasNext()) {

194                     parameterBuffer.append("&");

195                 }

196             }

197         }

198         return parameterBuffer.toString();

199     }

200

201     public static void main(String[] args) throws MalformedURLException {

202

203         System.out.println(requestMethod(HTTP_GET, "http://127.0.0.1:8080/test/TestHttpRequestServlet",

204                 "username=123&password=我是谁"));

205

206     }

207 }

测试Servlet

1 package com.servlet;

2

3 import java.io.IOException;

4

5 import javax.servlet.ServletException;

6 import javax.servlet.http.HttpServlet;

7 import javax.servlet.http.HttpServletRequest;

8 import javax.servlet.http.HttpServletResponse;

9

10 public class TestHttpRequestServelt extends HttpServlet {

11

12

13     @Override

14     protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

15

16         System.out.println("this is a TestHttpRequestServlet");

17         request.setCharacterEncoding("utf-8");

18

19         String username = request.getParameter("username");

20         String password = request.getParameter("password");

21

22         System.out.println(username);

23         System.out.println(password);

24

25         response.setContentType("text/plain; charset=UTF-8");

26         response.setCharacterEncoding("UTF-8");

27         response.getWriter().write("This is ok!");

28

29     }

30 }

web.xml配置

1 <?xml version="1.0" encoding="UTF-8"?>

2

3   test

4

5

6       TestHttpRequestServlet

7       com.servlet.TestHttpRequestServelt

8

9

10

11       TestHttpRequestServlet

12       /TestHttpRequestServlet

13

14

15

16     index.html

17     index.htm

18     index.jsp

19     default.html

20     default.htm

21     default.jsp

22

23

java的connect和http_【JAVA】通过URLConnection/HttpURLConnection发送HTTP请求的方法相关推荐

  1. 通过java.net.URLConnection发送HTTP请求的方法

    2019独角兽企业重金招聘Python工程师标准>>> 1.GET与POST请求的区别 a) get请求可以获取静态页面,也可以把参数放在URL字串后面,传递给servlet, b) ...

  2. JAVA通过HTTPS发送POST请求的方法

    因为调用一个外部接口,会用到POST请求,而且还是Https的,但是由于之前学习的时候没有用到,所以研究了很久才弄懂了怎么去用JAVA实现Https发送post请求 使用的是HttpsURLConne ...

  3. java使用Post方式发送https请求的方法,直接可以用

    踩过无数坑之后,成功的方案,主要在设置Content-type  application/x-www-form-urlencoded这里,之前没设置,一直数据不通过,不过好了现在OK了 URL req ...

  4. java 常见几种发送http请求案例

    java 常见几种发送http请求案例 直接换成CloseableHttpClient还不行,需要这样使用CloseableHttpClient httpClient = HttpClientBuil ...

  5. 通过java.net.URLConnection发送HTTP请求

    为什么80%的码农都做不了架构师?>>>    最常用的Http请求无非是get和post,get请求可以获取静态页面,也可以把参数放在URL字串后面,传递给服务器,post与get ...

  6. java 转发上传文件_Java 发送http请求上传文件功能实例

    废话不多说了,直接给大家贴代码了,具体代码如下所示: package wxapi.WxHelper; import java.io.BufferedReader; import java.io.Dat ...

  7. Java发送Http请求,解析html返回

    今天是2008年7月7日星期一,下午一直在学校做个人开始页面.因为离不开google的翻译,所以想把google的翻译整合到我的开始页面中来,于是乎就遇到了一个问题,怎样使用java程序发送http请 ...

  8. Java学习系列(十六)Java面向对象之基于TCP协议的网络通信

    TCP/IP的网络分层模型:应用层(HTTP/FTP/SMTP/POPS...),传输层(TCP协议),网络层(IP协议,负责为网络上节点分配唯一标识),物理层+数据链路层). IP地址用于标识网络中 ...

  9. 尚硅谷Java入门视频教程(在线答疑+Java面试真题)

    Java核心技术 一.Java基本语法 1.关键字与保留字 关键字的定义和特点 被Java语言赋予了特殊含义,用做专门用途的字符串(单词) 关键字中所有字母都为小写 保留字的定义 现有Java版本尚未 ...

最新文章

  1. 【FPGA】SRIO IP核系统介绍之事务类型(Transaction)
  2. 浅玩JavaScript的数据类型判断
  3. oracle中的备注的配置与查询
  4. yoman不压缩html,使用Yeoman构建vuejs
  5. C++STL特殊容器priority_queue
  6. 合流超几何函数_【CV】CVPR2020丨SPSR:基于梯度指导的结构保留超分辨率方法
  7. 基于JAVA+Servlet+JSP+MYSQL的新闻发布系统
  8. C#的排序算法以及随机产生不重复数字的几个Demo
  9. ImportError: libgfortran.so.4: cannot open shared object file: No such file or directory
  10. appiumpython框架实例_GitHub - feiyangzhu/python-appium: 基于PageObject UI自动化测试框架,支持Android/iOS...
  11. SVN 版本回退 命令行
  12. excel查找命令_快速查找Excel功能区命令
  13. 弘辽科技:淘宝类目属性的型号是什么?
  14. 劳务派遣与劳务外包的主要区别
  15. Conda太慢 试试这个加速工具
  16. 检索 COM 类工厂中 CLSID 为 {00024500-0000-0000-C000-000000000046} 的组件时失败,原因是出现以下错误: 80070005
  17. Telnet 1521端口连接失败问题,经过四天的努力终于解决!
  18. HTML之form表单
  19. GPS时钟系统(GPS时钟同步系统-GPS时间同步系统)
  20. OTFS从零开始(一)

热门文章

  1. Android打开相机进行人脸识别,使用虹软人脸识别引擎
  2. weak引用表原理探究
  3. 多线程中的静态代理模式
  4. 【LeetCode】168. Excel Sheet Column Title 解题小结
  5. Linux下C程序进程地址空间布局[转]
  6. JavaScript 模拟重载
  7. 类 ArrayBlockingQueueE(一个由数组支持的有界阻塞队列。)
  8. 获取FileUpload上传的文件大小
  9. 一个JavaScript读取XML的问题
  10. 让医生能更好诊断患者风险 英国剑桥大学开发心脏病预测AI