the5fire

关注Python、Django、Vim、Linux、Web开发、团队管理和互联网--Life is short, we need Python.


android和javaEE更完美的通信-传递对象

作者:the5fire | 标签:       | 发布:2011-07-15 5:30 p.m. | 阅读量: 8482, 8233
继续完善上一篇中的那个代码片,《android和javaEE通信的代码片》中只是简单的向服务器发送请求,没有获取服务器返回数据的操作。
继续看着新浪SDK中的代码,它是通过json来实现的,其实说json,不过是一种数据格式,就算是服务器端传送过来一样要本地解析成数组(新浪是这么做的),代码实现思路到不复杂,只要把json字符串放到json类中(这个类是json提供的),可直接转换对象,或者数组。
不过考虑到新浪是由android和php服务器端进行通信的,json必然是一个简单的方法。但是对于android和javaEE服务器端通信,用json的话还是需要一些操作来处理的,不如直接在网络中传递java对象来的方便(当然,仅仅是一个小实验,两者的安全性如何还不知晓)。
于是写下这些代码,供以后参考:
需要提示的一点:在网络上传递的类,在两端一定要属于相同的包,最起码所属的的包名应该一样。
HttpClient.java:

import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

public class HttpClient {
public static Response httpRequest(String url, PostParameter[] postParams,
String httpMethod) {
int responseCode = -1;
Response res = null;

try {
HttpURLConnection con = null;
OutputStream osw = null;
try {
con = (HttpURLConnection) new URL(url).openConnection();

con.setDoInput(true);
if (null != postParams || "POST".equals(httpMethod)) {
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
con.setDoOutput(true);
String postParam = "";
if (postParams != null) {
postParam = encodeParameters(postParams);
}
byte[] bytes = postParam.getBytes("UTF-8");

con.setRequestProperty("Content-Length",
Integer.toString(bytes.length));
osw = con.getOutputStream();
osw.write(bytes);
osw.flush();
osw.close();
}
responseCode = con.getResponseCode();

res = new Response(con);

} finally {

}
} catch (Exception e){
e.printStackTrace();
}
return res;
}

private static String encodeParameters(PostParameter[] postParams) {
StringBuffer buf = new StringBuffer();
for (int j = 0; j < postParams.length; j++) {
if (j != 0) {
buf.append("&");
}
try {
buf.append(URLEncoder.encode(postParams[j].getName(), "UTF-8"))
.append("=").append(URLEncoder.encode(postParams[j].getValue(), "UTF-8"));
} catch (java.io.UnsupportedEncodingException neverHappen) {
}
}
return buf.toString();
}

public static void main(String[] args) {
PostParameter[] postParameters = new PostParameter[1];
postParameters[0] = new PostParameter("loginName","demo");
Response res = httpRequest("http://localhost:8090/mlabs/user/checkLoginName.action", postParameters,
"POST");
System.out.println("获得服务器端返回对象:" + res.getObjectList());
}
}

PostParamenter.java

public class PostParameter implements java.io.Serializable, Comparable {

/**
*
*/
private static final long serialVersionUID = 1L;

@Override
public int compareTo(Object o) {
// TODO Auto-generated method stub
return 0;
}

public PostParameter(String name, String value) {
super();
this.name = name;
this.value = value;
}
public PostParameter(){

}
private String name;
private String value;

public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}

Response.java

public class Response {
private HttpURLConnection con = null;

public Response(){ }

public Response(HttpURLConnection con) {
this.con = con;
}

/**
* 获取数据
*/
public List getObjectList() {
InputStream is;
List stus = null;
try {
is = con.getInputStream();
ObjectInputStream ois = new ObjectInputStream(is);
stus = (List)ois.readObject();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return stus;
}
}

Student.java

public class Student implements java.io.Serializable, Comparable {
private static final long serialVersionUID = 1L;

public int compareTo(Object o) {
// TODO Auto-generated method stub
return 0;
}

private String name;
private int age;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}

@Override
public String toString() {
return "Student [name=" + name + ", age=" + age + "]";
}
}

另外在服务器端返回数据的代码片段,我是写在一个Action中的:

System.out.println("loginName:"+loginName);
HttpServletRequest request = ServletActionContext.getRequest();
HttpServletResponse response = ServletActionContext.getResponse();
response.setCharacterEncoding("UTF-8");
response.setContentType("text/plain");
Student student = new Student();
student.setName("huyang");
student.setAge(24);
Student student1 = new Student();
student1.setName("the5fire");
student1.setAge(21);
List list = new ArrayList(2);
list.add(student);

list.add(student1);
System.out.println(list);
//TODO 仅仅为了测试
OutputStream outs = response.getOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(outs);
oos.writeObject(list);
return null;

最终结果展示:


因为我的服务器端项目是在IDEA中,这个工具里面集成的tomcat无法提供外网方法地址,因此无法在android中测试。大家可自行测试,有问题还望告知我一声。感谢!

PS:刚才新写了一个简单的javaEE项目,用android测试了一下,可以得到同样的结果。 - from the5fire.com
----EOF-----

微信公众号:Python程序员杂谈


其他分类: