Java 使用流的方式发送、接收 HTTP 请求

发送 HTTP 请求,net 下的包

public static void main(String[] args) throws Exception {
          
   
		URL url = new URL("地址");
		HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();	
		urlConnection.setReadTimeout(5000);		// 设置读取时长
		urlConnection.setConnectTimeout(5000);	// 设置连接时长
		urlConnection.setRequestProperty("Content-Type", "application/json");	// 设置头
		urlConnection.setRequestMethod("POST");	// 请求方式,需要大写,小写会抛出异常
		/**
		 * 如果打算使用 URL 连接进行输出,则将 DoOutput 标志设置为 true;如果不打算使用,则设置为 false。
		 */
		urlConnection.setDoOutput(true);		// 默认为 false。
		/**
		 * 如果打算使用 URL 连接进行输入,则将 DoInput 标志设置为 true;如果不打算使用,则设置为 false
		 */
		urlConnection.setDoInput(true);			// 默认为 true
		BufferedOutputStream bos = new BufferedOutputStream(urlConnection.getOutputStream());	// 建立发送流
		bos.write("发送内容".getBytes("utf-8"));	// 写入缓存
		bos.flush();							// BufferedOutputStream 需要调用 flush 方法才会真正发送
		BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));	// 建立读取流
		StringBuffer sb = new StringBuffer();
		String data = null;
		while ((data = reader.readLine()) != null) {
          
   
			sb.append(data);
		}
		String message = sb.substring(0, sb.length());
		System.out.println(message);
	}

接收 HTTP 请求

public String resviceMsg(HttpServletRequest rquest, HttpServletResponse response) throws Exception {
          
   
		BufferedReader br = null;
		try {
          
   
			br = new BufferedReader(new InputStreamReader(rquest.getInputStream(), "utf-8"));	// 建立读取流
			StringBuffer sb = new StringBuffer();
			String data = null;
			while ((data = reader.readLine()) != null) {
          
   
				sb.append(data);
			}
			System.out.println(0, sb.length());
			response.setCharacterEncoding("utf-8");		// 设置字符集编码
			response.getWriter().println("返回内容");
		} catch(Exception e){
          
   
			System.out.println("错误信息:" + e.getMessage());
		} finally {
          
   
			if(br != null) br.close();
		}
		return null;
	}
经验分享 程序员 微信小程序 职场和发展