Sending a serialized object from Android to a servlet using HTTP client
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();
}
}
}
Asked by: Adelaide572 | Posted: 20-01-2022
Answer 1
As suggested, use XML or JSON. You can get XStream patched for Android from this blog in order to serialize your objects to XML.
Answered by: Jack311 | Posted: 21-02-2022Answer 2
Don't use serialization between architectures. Use JSON, XML, or something else that is architecture-neutral.
Answered by: Audrey441 | Posted: 21-02-2022Answer 3
I second the suggestion of XStream. It is a very nice and easy API. I don't like the Serialization formats XML or JSON though because they are text based. For a more compact serialization format, try ProtoBuf from Google.
Answered by: Wilson118 | Posted: 21-02-2022Similar questions
Sending serialized data from android to java
I want to send class variables from android device to server.
In my server java program receives requests with socket connection
I want to use xml serializer . I couldn't find any xml serializer that was supported both java platforms , jre and android .
I can use different xml serializer libraries in android and java . But i worry about two different serializer library can not read each others seri...
Sending Serialized Object from java server to android client
android - Sending serialized file via other apps
Hello I made serialized object file and I want to send it via , messenger, gmail, sms, etc. I tried to send it in this way, this is code from saving to sending. I got that no one app is connected with this.
File file=new File(getFilesDir() + "ShoppingList.ur");
try{
FileOutputStream fileOutputStream =new FileOutputStream(file);
ObjectOutputStream data=...
android - Reading Java serialized object that has been split across two files?
I'm writing an Android application. One problem is your app cannot contain a file whose uncompressed size is bigger than about 1Mb. I have a serialized object that I want to load that totals about 2Mb. My plan was to split this file into two smaller files, then load the object by combining both files at runtime.
However, I cannot work out how to use e.g. InputStream and ObjectInputStream to specify that I want to r...
How to attach EXIF metadata to a serialized Bitmap in Android?
In Android, when decoding a Bitmap from a photo on the phone, the EXIF data in the original gets lost. I am sending this Bitmap to my server via a socket and would like to re-attach the missing EXIF data to the data being sent.
I have some code that loads a Bitmap object from the MediaStore and compresses it to a byte array in preparation to send it over a socket:
android - Jackson JSON java class - fields are serialized multiple times
I have a following class defined
@JsonTypeName("PhotoSetUpdater")
public class PhotoSetUpdater {
@JsonProperty("Title")
private String title;
@JsonProperty("Caption")
private String caption;
@JsonProperty("Keywords")
private String[] keywords;
@JsonProperty("Categories")
private int[] categories;
@JsonProperty("CustomReference")
private String customReference; // new in version 1.1
public String ...
android storing an arraylist of serialized objects in a file
I want to store an arraylist of objects in a file in order to reach them after the app is opened again.
public class SmsMessage implements Serializable {
public static enum MessageType {
Sent,
Received;
};
private String body;
private Date date;
private MessageType type;
public SmsMessage(String _body, Date _date, MessageType _type) {
body = _body;
...
android - Saving my Serialized Class that have not serialized objects like Rect
I'm trying to save my Serialized object when the activity calls the onDestroy() but when i try to write my object using ObjectOutputStream a java.io.NotSerializableExeption is thrown.
Can you please help me. Thanks
android - how do you stop a variable from being Serialized?
EG
public class SomeObject implements Serializable {
private static final long serialVersionUID = -5394297791806714290L;
private long m_id;
private String m_name;
private String m_blah;
}
How would you stop m_blah from being serialized?
Android ormlite update rows in Serialized Object
I have 3 tables:
@DatabaseTable(tableName="user")
public class TableUser implements Serializable{
@DatabaseField(dataType = DataType.SERIALIZABLE)
private LinkedList<TableProfile> profiles;
}
@DatabaseTable(tableName="profile")
public class TableProfile implements Serializable{
@DatabaseField(dataType = DataType.SERIALIZABLE)
private LinkedList<TableRevel> revelations;
}
@Datab...
java - issue involving serialized object and eclipse
I have a Serializable object that I am sending from my android emulator to a java server on the same computer. I have been able to send raw data but when I send the object I have an issue. The issue is that I have made the server in textpad and the androind app in eclips. The the object the server is looking for is of type point but eclipse is adding the file structure to it. ie help.help.point. Do I need to put all my fil...
Sending serialized data from android to java
I want to send class variables from android device to server.
In my server java program receives requests with socket connection
I want to use xml serializer . I couldn't find any xml serializer that was supported both java platforms , jre and android .
I can use different xml serializer libraries in android and java . But i worry about two different serializer library can not read each others seri...
android - save serialized object in phone memory
Here i have some data which i want to store in phone memory and retrieve when necessary
here is the code:
public void saveObject(Person p){
try
{
FileOutputStream fos = openFileOutput("save_object.bin", Context.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(p); // write the class as an 'object'
oos.flush(); // flus...
Still can't find your answer? Check out these communities...
Android Google Support | Android Community | Android Community (Facebook) | Dev.io Android