使用HTTP客户端从Android的发送序列化对象到一个servlet [英] Sending a serialized object from Android to a servlet using HTTP client
问题描述
我试图创建发送serialzed对象从手机到一个servlet对象的内容是,我将存储在数据库中使用Hibernate用户输入一个Android应用程序。我相信问题是围绕对象的串行化和反串行化的code是如下。如果有人可以帮助我将非常感激。
PS类用户实现Serializable接口
客户端
公共类adduser的延伸活动实现OnClickListener {
EditText上的uname;
的EditText密码;
的EditText评级;
的EditText日期;
按钮添加;
用户的用户;
@覆盖
公共无效的onCreate(包savedInstanceState){
super.onCreate(savedInstanceState);
的setContentView(R.layout.main);
的uname =(EditText上)findViewById(R.id.Usernamei);
密码=(EditText上)findViewById(R.id.passwordi);
等级=(EditText上)findViewById(R.id.ratingi);
日期=(EditText上)findViewById(R.id.datei);
添加=(按钮)findViewById(R.id.Adduser);
用户=新用户();
add.setOnClickListener(本);
}
@覆盖
公共无效的onClick(视图v){
user.setusername(uname.getText()的toString());
user.setpassword(password.getText()的toString());
user.setdate(date.getText()的toString());
user.setrating(rating.getText()的toString());
HttpClient的HttpClient的=新DefaultHttpClient();
ObjectOutput的了;
尝试{
字符串URL =我的网址放在这里;
HttpPost后=新HttpPost(URL);
//对象的序列化
ByteArrayOutputStream BOS =新ByteArrayOutputStream();
OUT =新的ObjectOutputStream(BOS);
out.writeObject(用户);
//把字节为对象,它是在HTTP请求的主体
post.setHeader(新BasicHeader(内容长度,+ bos.toByteArray()的长度));
ByteArrayEntity巴尔=新ByteArrayEntity(bos.toByteArray());
//设置请求的主体
post.setEntity(巴尔);
out.close();
//执行请求,并返回一个响应
HTT presponse响应= httpClient.execute(后);
}赶上(IOException异常E){
Log.e(哎哟,!!! IOException异常+ e.getMessage());
}
uname.setText(将String.valueOf());
password.setText(将String.valueOf());
rating.setText(将String.valueOf());
date.setText(将String.valueOf());
}
}
服务器端
公共类adduser的延伸的HttpServlet {
//记录器的属性文件
//私有静态记录器记录器= Logger.getLogger(Adduser.class);
公共无效的doPost(HttpServletRequest的请求,HttpServletResponse的响应)抛出了ServletException {
//测试
//logger.warn("this是一个示例日志信息)。
字符串用户N = NULL;
字符串password = NULL;
串等级= NULL;
字符串日= NULL;
在的InputStream;
尝试 {
//获取HTTP内容主体的字节数组应该是在流
在= request.getInputStream();
// INT bytesToRead;
// bytesToRead =的Integer.parseInt(request.getHeader(内容长度));
//读取inputream内容写入字节组
INT读取动作= 0;
INT bytesToRead = 1024;
byte []的输入=新的字节[bytesToRead]
而(读取动作< bytesToRead){
INT结果= in.read(输入,读取动作,bytesToRead - 读取动作);
如果(结果== -1)打破;
读取动作+ =结果;
}
//通过字节数组传递到的ObjectInput流
ObjectInputStream的客栈=新的ObjectInputStream(新ByteArrayInputStream的(输入));
用户用户= NULL;
尝试 {
//对象读入用户对象和投
用户=(用户)inn.readObject();
}赶上(ClassNotFoundException的E1){
// TODO自动生成的catch块
的System.out.println(e1.getMessage());
}
附寄();
inn.close();
//对象的内容放入变量要传递到数据库
用户N = users.getusername();
密码= users.getpassword();
等级= users.getrating();
日期= users.getdate();
}赶上(IOException异常E2){
// TODO自动生成的catch块
的System.out.println(e2.getMessage());
}
会话会话= NULL;
尝试{
SessionFactory的SessionFactory的=新配置()配置()buildSessionFactory()。
会议= sessionFactory.openSession();
//创建联系人的新实例,并设置
交易TX = session.beginTransaction();
Userr用户=新Userr();
user.setusername(用户N);
user.setpassword(密码);
user.setrating(等级);
user.setdate(日期);
的session.save(用户);
tx.commit();
}赶上(例外五){
的System.out.println(e.getMessage());
}最后{
//实际接触的插入会发生在这个步骤
session.flush();
session.close();
}
}
}
作为建议,使用XML或JSON。 你可以得到 XStream的修补Android版的从为了这个博客您的对象序列化到XML。
I have tried to create a android application that sends a serialzed object from the phone to a servlet the contents of the object is the input from the user which i will store in a database using hibernate. I believe the problem is around the serializing and deserializing of the object the code is below. If anyone could help i would very greatful.
p.s the class User implements the serializable interface
client
public class Adduser extends Activity implements OnClickListener {
EditText uname;
EditText password;
EditText rating;
EditText date;
Button add;
User user;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
uname = (EditText) findViewById(R.id.Usernamei);
password = (EditText) findViewById(R.id.passwordi);
rating = (EditText) findViewById(R.id.ratingi);
date = (EditText) findViewById(R.id.datei);
add = (Button) findViewById(R.id.Adduser);
user = new User();
add.setOnClickListener(this);
}
@Override
public void onClick(View v) {
user.setusername(uname.getText().toString());
user.setpassword(password.getText().toString());
user.setdate(date.getText().toString());
user.setrating(rating.getText().toString());
HttpClient httpClient = new DefaultHttpClient();
ObjectOutput out;
try{
String url = "MY URL goes here";
HttpPost post = new HttpPost(url);
//Serialisation of object
ByteArrayOutputStream bos = new ByteArrayOutputStream() ;
out = new ObjectOutputStream(bos) ;
out.writeObject(user);
//puts bytes into object which is the body of the http request
post.setHeader(new BasicHeader("Content-Length", "" + bos.toByteArray().length));
ByteArrayEntity barr = new ByteArrayEntity(bos.toByteArray());
//sets the body of the request
post.setEntity(barr);
out.close();
//executes request and returns a response
HttpResponse response = httpClient.execute(post);
} catch (IOException e) {
Log.e( "ouch", "!!! IOException " + e.getMessage() );
}
uname.setText(String.valueOf(""));
password.setText(String.valueOf(""));
rating.setText(String.valueOf(""));
date.setText(String.valueOf(""));
}
}
Server side
public class Adduser extends HttpServlet {
//logger for properties file
//private static Logger logger = Logger.getLogger(Adduser.class);
public void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException {
//test
//logger.warn("this is a sample log message.");
String usern = null;
String password = null;
String rating = null;
String date = null;
InputStream in;
try {
//gets http content body byte array should be on the stream
in = request.getInputStream();
//int bytesToRead;
//bytesToRead = Integer.parseInt(request.getHeader("Content-Length"));
//reads inputream contents into bytearray
int bytesRead=0;
int bytesToRead=1024;
byte[] input = new byte[bytesToRead];
while (bytesRead < bytesToRead) {
int result = in.read(input, bytesRead, bytesToRead - bytesRead);
if (result == -1) break;
bytesRead += result;
}
//passes byte array is passed into objectinput stream
ObjectInputStream inn = new ObjectInputStream(new ByteArrayInputStream(input));
User users = null;
try {
//object is read into user object and cast
users = (User)inn.readObject();
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
System.out.println(e1.getMessage());
}
in.close();
inn.close();
//contents of object is put into variables to be passed into database
usern = users.getusername();
password = users.getpassword();
rating = users.getrating();
date = users.getdate();
} catch (IOException e2) {
// TODO Auto-generated catch block
System.out.println(e2.getMessage());
}
Session session = null;
try{
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
session = sessionFactory.openSession();
//Create new instance of Contact and set
Transaction tx = session.beginTransaction();
Userr user = new Userr();
user.setusername(usern);
user.setpassword(password);
user.setrating(rating);
user.setdate(date);
session.save(user);
tx.commit();
}catch(Exception e){
System.out.println(e.getMessage());
}finally{
// Actual contact insertion will happen at this step
session.flush();
session.close();
}
}
}
As suggested, use XML or JSON. You can get XStream patched for Android from this blog in order to serialize your objects to XML.
这篇关于使用HTTP客户端从Android的发送序列化对象到一个servlet的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!