本片文章将给出一个传输对象序列化字节流的实例,实际上对上篇文章的代码稍作修改即可。过程如下:
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());
}