Java应用层同步通信HttpURLConnection+Servlet(二)

本片文章将给出一个传输对象序列化字节流的实例,实际上对上篇文章的代码稍作修改即可。过程如下:

1.在client端和servlet建立相同存根,实现了Serializable接口的User类,注意:包路径也要相同的。代码如下:

package com.cugxw.http.vo;

import java.io.Serializable;

public class User implements Serializable {
	private static final long serialVersionUID = 1L;
	
	private String username;
	private String password;
	
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
}

 

2.服务器端接收字节流并转化为对象打印出来,然后返回一个普通字符串response,代码如下:

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		//Get input stream from client
		InputStream inStream = req.getInputStream();
		ObjectInputStream objInStream = new ObjectInputStream(inStream);
		
		User user = null;
		try {
			user = (User)objInStream.readObject();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		System.out.println("username=" + user.getUsername() + "\r\n" + "password=" + user.getPassword());
				
		/* Response to client */
		OutputStream os = resp.getOutputStream();
		OutputStreamWriter writer = new OutputStreamWriter(os);
		
		writer.write("response");
		writer.flush();
		writer.close();
	}

3.客户端发送一个User对象并接收服务端返回的字符串,代码如下:

	public static void main(String[] args) throws Exception {
		//Set up a url
		URL url = new URL("http://localhost:8088/Servlet/httpConnectionServletTest");
		
		//Generate url connection
		URLConnection urlConn = url.openConnection();
		
		//Switch to http url connection
		HttpURLConnection httpUrlConn = (HttpURLConnection) urlConn;
		
		/* Output into http connection or not.
		 * If send get request, the parameter is false;
		 * If send post request, the parameter is true; */
		httpUrlConn.setDoOutput(true);
		
		//Input into http connection or not.
		httpUrlConn.setDoInput(true);
		
		//User cache or not
		httpUrlConn.setUseCaches(false);
		
		//Request context type is java serialized object
		httpUrlConn.setRequestProperty("Content-type", "application/x-java-serialized-object");
				
		//Set request method
		httpUrlConn.setRequestMethod("POST");
		
		//Get tcp connection
		httpUrlConn.connect();
		
		//get output stream object
		OutputStream outputStream = httpUrlConn.getOutputStream();
		
		//output java serialized object
		ObjectOutputStream objOutputStream = new ObjectOutputStream(outputStream);
		
		User user = new User();
		user.setUsername("cugxw");
		user.setPassword("123456");
		
		//write object into memory buffer area
		objOutputStream.writeObject(user);
		
		//Flush the memory buffer and put the object into output stream
		objOutputStream.flush();
		
		objOutputStream.close();
				
		//Invoke method getInputStream() to send data to server
		InputStream inStream = httpUrlConn.getInputStream();
		
		/* Get response from server 
		 * You can invoke available method to get the length of stream */
		byte[] inB = new byte[inStream.available()];
		inStream.read(inB);
		System.out.println((new String(inB)).toString());
	}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要通过JSP和Servlet获取当前天气,需要使用一些API来获取天气信息。以下是实现的一般步骤: 1. 注册并获取天气API的访问密钥,例如使用百度API Store提供的免费天气API。 2. 在JSP页面中引入jQuery库和自定义的JavaScript脚本文件,用于实现异步获取天气信息并更新页面。 3. 在JSP页面中添加一个用于显示天气信息的HTML元素,例如标签。 4. 在自定义的JavaScript脚本文件中编写异步请求天气API的方法,并处理返回的JSON格式的数据。 5. 在Servlet中处理异步请求,获取天气信息并返回JSON格式的数据。 以下是一个简单的示例代码: JSP页面代码: ```html <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>获取当前天气</title> <script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script> <script src="getWeather.js"></script> </head> <body> <h1>当前天气</h1> <div id="weather"></div> </body> </html> ``` 自定义JavaScript脚本文件代码(getWeather.js): ```javascript $(document).ready(function() { getWeather(); }); function getWeather() { $.ajax({ url: "weather", success: function(data) { var weather = data.weather[0].description; var temp = data.main.temp; var humidity = data.main.humidity; $("#weather").html("天气:" + weather + ",温度:" + temp + ",湿度:" + humidity); }, error: function() { $("#weather").html("无法获取天气信息"); } }); } ``` Servlet代码: ```java import java.io.IOException; import java.io.PrintWriter; import java.net.HttpURLConnection; import java.net.URL; import java.util.Scanner; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.json.JSONObject; public class WeatherServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("application/json;charset=UTF-8"); PrintWriter out = response.getWriter(); String key = "your_api_key"; // 替换为你的API访问密钥 String city = "Beijing"; // 替换为你要获取天气的城市 String apiUrl = "http://api.openweathermap.org/data/2.5/weather?q=" + city + "&appid=" + key; URL url = new URL(apiUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("Accept", "application/json"); Scanner scanner = new Scanner(conn.getInputStream()); String result = ""; while (scanner.hasNext()) { result += scanner.nextLine(); } scanner.close(); JSONObject json = new JSONObject(result); out.print(json); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } } ``` 需要注意的是,以上示例代码仅供参考,实际使用时需要根据具体情况进行适当的修改和调整。同时,也需要考虑API的访问限制和使用限制,避免超出免费使用额度或违反相关规定。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值