使用HttpURLConnection类不仅可以向WebService发送字符串,还可以发送序列化的java对象,实现Android手机和服务器之间的数据交互。
Android端代码:
public String SendDataByPost(String urlStr){
URL url = null;
String result="";//要返回的结果
try {
url=new URL(urlStr);
HttpURLConnection httpURLConnection= (HttpURLConnection) url.openConnection(); httpURLConnection.setConnectTimeout(2000);//设置连接超时时间,单位ms
httpURLConnection.setReadTimeout(2000);//设置读取超时时间,单位ms //设置是否向httpURLConnection输出,因为post请求参数要放在http正文内,所以要设置为true
httpURLConnection.setDoOutput(true); //设置是否从httpURLConnection读入,默认是false
httpURLConnection.setDoInput(true); //POST请求不能用缓存,设置为false
httpURLConnection.setUseCaches(false); //传送的内容是可序列化的
//如果不设置此项,传送序列化对象时,当WEB服务默认的不是这种类型时,会抛出java.io.EOFException错误
httpURLConnection.setRequestProperty("Content-type","application/x-java-serialized-object"); //设置请求方法是POST
httpURLConnection.setRequestMethod("POST"); //连接服务器
httpURLConnection.connect(); //getOutputStream会隐含调用connect(),所以不用写上述的httpURLConnection.connect()也行。
//得到httpURLConnection的输出流
OutputStream os= httpURLConnection.getOutputStream(); //构建输出流对象,以实现输出序列化的对象
ObjectOutputStream objOut=new ObjectOutputStream(os); //dataPost类是自定义的数据交互对象,只有两个成员变量
dataPost data= new dataPost("Tom",null); //向对象输出流写出数据,这些数据将存到内存缓冲区中
objOut.writeObject(data); //刷新对象输出流,将字节全部写入输出流中
objOut.flush(); //关闭流对象
objOut.close();
os.close(); //将内存缓冲区中封装好的完整的HTTP请求电文发送到服务端,并获取访问状态
if(HttpURLConnection.HTTP_OK==httpURLConnection.getResponseCode()){ //得到httpURLConnection的输入流,这里面包含服务器返回来的java对象
InputStream in=httpURLConnection.getInputStream(); //构建对象输入流,使用readObject()方法取出输入流中的java对象
ObjectInputStream inObj=new ObjectInputStream(in);
data= (dataPost) inObj.readObject(); //取出对象里面的数据
result=data.password; //输出日志,在控制台可以看到接收到的数据
Log.w("HTTP",result+" :by post"); //关闭创建的流
in.close();
inObj.close();
}else{
Log.w("HTTP","Connction failed"+httpURLConnection.getResponseCode());
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
package com.example.com.example.data; import java.io.Serializable; //实现Serializable接口,使dataPost可序列化。
public class dataPost implements Serializable { /*指定序列化版本号,保证序列化版本的一致性。在服务器端,JVM会把传来的字节流的
serialVersionUID与本地相应实体(类)的serialVersionUID进行比较,如果相同就认
为是一致的,可以进行反序列化,否则就会出现序列化版本不一致的异常。*/
private static final long serialVersionUID = 1L; String name;
String password;
public dataPost(String name, String password) {
this.name = name;
this.password = password;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public String getPassword() {
return password;
} public void setPassword(String password) {
this.password = password;
} }
服务端程序:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ServletInputStream in=request.getInputStream();
dataPost datap = null;
ObjectInputStream obj=new ObjectInputStream(in);
try {
datap= (dataPost) obj.readObject();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}finally{
obj.close();
}
response.setContentType("application/x-java-serialized-object");
OutputStream out=response.getOutputStream();
ObjectOutputStream outObj=new ObjectOutputStream(out);
datap.setPassword("9964646");
outObj.writeObject(datap);
outObj.flush();
outObj.close();
}
注意事项:
1、客户端url如果有中文会出现乱码,需要对url进行编码。
例如:
String url="你好";
URI uri=new URI(url,false,"utf-8");
url=uri.toString();
2、在Android主程序中调用SendDataByPost()方法时,要重新开一个线程,否则会阻塞主线程。
new Thread(new Runnable() {
@Override
public void run() {
HTTPURLConnectionGETData getData = new HTTPURLConnectionGETData();
String result=getData.SendStringDataByPost(serverIP1);
if("".equals(result)){
}else{
Log.i("HTTP",result);
}
}
}).start();
3、Android端dataPost类的包名和server端dataPost的包名必须一致,否则就会出现找不到该类的异常。
java.lang.ClassNotFoundException: com.example.com.example.data.dataPost
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1333)
4、Android端dataPost类的包名和server端dataPost的序列化版本必须一致,否则会报出serialVersionUID不同的错误。
Servlet.service() for servlet [com.test.stream.testStream] in context with path [/campus2] threw exception
java.io.InvalidClassException: com.example.com.example.data.dataPost; local class incompatible:
stream classdesc serialVersionUID = -1197271749879367300, local class serialVersionUID = -3085829960977977003
解决方法:
在两端的dataPost类中显式的指定序列化版本号,一般通过添加private static final long serialVersionUID = 1L实现。