Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/184.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 使用HTTP客户端从Android向servlet发送序列化对象_Java_Android_Serialization_Httpclient - Fatal编程技术网

Java 使用HTTP客户端从Android向servlet发送序列化对象

Java 使用HTTP客户端从Android向servlet发送序列化对象,java,android,serialization,httpclient,Java,Android,Serialization,Httpclient,我曾尝试创建一个android应用程序,它将一个序列化对象从手机发送到一个servlet。该对象的内容是来自用户的输入,我将使用hibernate将其存储在数据库中。我相信问题在于下面代码中对象的序列化和反序列化。如果有人能帮助我,我将不胜感激 p、 s类用户实现可序列化接口 客户 public class Adduser extends Activity implements OnClickListener { EditText uname; EditText password;

我曾尝试创建一个android应用程序,它将一个序列化对象从手机发送到一个servlet。该对象的内容是来自用户的输入,我将使用hibernate将其存储在数据库中。我相信问题在于下面代码中对象的序列化和反序列化。如果有人能帮助我,我将不胜感激

p、 s类用户实现可序列化接口

客户

    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();

        }

 }




 }
public类Adduser扩展活动实现OnClickListener{
编辑文本联塞特派团;
编辑文本密码;
编辑文本评级;
编辑文本日期;
按钮添加;
用户;
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
uname=(EditText)findViewById(R.id.Usernamei);
密码=(EditText)findViewById(R.id.passwordi);
评级=(编辑文本)findViewById(R.id.ratingi);
日期=(EditText)findViewById(R.id.datei);
add=(按钮)findViewById(R.id.Adduser);
user=新用户();
add.setOnClickListener(这个);
}
@凌驾
公共void 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();
对象输出;
试一试{
String url=“我的url在这里”;
HttpPost=新的HttpPost(url);
//对象序列化
ByteArrayOutputStream bos=新建ByteArrayOutputStream();
out=新对象输出流(bos);
out.writeObject(用户);
//将字节放入作为http请求主体的对象中
post.setHeader(新的BasicHeader(“内容长度”,“bos.toByteArray().Length”);
ByteArrayEntity barr=新的ByteArrayEntity(bos.toByteArray());
//设置请求的主体
邮政实体(barr);
out.close();
//执行请求并返回响应
HttpResponse response=httpClient.execute(post);
}捕获(IOE异常){
Log.e(“哎哟”,“!!!IOException”+e.getMessage());
}
uname.setText(String.valueOf(“”);
password.setText(String.valueOf(“”);
rating.setText(String.valueOf(“”);
date.setText(字符串.valueOf(“”);
}
}
服务器端
公共类Adduser扩展HttpServlet{
//属性文件的记录器
//私有静态记录器=Logger.getLogger(Adduser.class);
public void doPost(HttpServletRequest请求、HttpServletResponse响应)抛出ServletException{
//试验
//warn(“这是一条示例日志消息”);
字符串usern=null;
字符串密码=null;
字符串评级=空;
字符串日期=空;
输入流输入;
试一试{
//获取http内容正文字节数组应位于流上
in=request.getInputStream();
//int-bytesToRead;
//bytesToRead=Integer.parseInt(request.getHeader(“内容长度”);
//将inputream内容读入bytearray
int字节读取=0;
int bytesToRead=1024;
字节[]输入=新字节[bytesToRead];
while(bytesRead
不要在体系结构之间使用序列化。使用JSON、XML或其他与体系结构无关的东西。

按照建议,使用XML或JSON。
为了将对象序列化为XML,可以为Android打补丁。

我支持XStream的建议。这是一个非常好和简单的API。我不喜欢序列化格式XML或JSON,因为它们是基于文本的。要获得更紧凑的序列化格式,请尝试从Google获得。

如果OP控制servlet,为什么它需要与体系结构无关?@Rick:servlet不是问题所在。客户是问题所在。现在,OP严格考虑的是Android。首先,无法保证Android的序列化格式与服务器的序列化格式相同,因为它们运行的运行时不同。其次,序列化只可能与Java-ish客户端一起工作,消除了iOS、Windows Phone、Symbian、Javascript(WebOS、AJAX/HTML5)、Flash或任何非Java桌面环境。聪明的程序员把自己限制在尽可能少的角落里。