继续完善上一篇中的那个代码片,《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 classHttpClient {
public staticResponse httpRequest ( Stringurl, PostParameter [ ]postParams,
StringhttpMethod ) {
intresponseCode = - 1 ;
Response res = null ;

try {
HttpURLConnectioncon = null ;
OutputStreamosw = 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 ) ;
StringpostParam = "" ;
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 = newResponse (con ) ;

} finally {

}
} catch ( Exceptione ) {
e. printStackTrace ( ) ;
}
returnres ;
}

private static StringencodeParameters (PostParameter [ ]postParams ) {
StringBufferbuf = new StringBuffer ( ) ;
for ( intj = 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. UnsupportedEncodingExceptionneverHappen ) {
}
}
returnbuf. toString ( ) ;
}

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

PostParamenter.java

public classPostParameter implementsjava. io. Serializable, Comparable {

/**
*
*/

private static final longserialVersionUID =1L ;

@Override
public intcompareTo ( Objecto ) {
// TODO Auto-generated method stub
return 0 ;
}

publicPostParameter ( Stringname, Stringvalue ) {
super ( ) ;
this. name =name ;
this. value =value ;
}
publicPostParameter ( ) {

}
private Stringname ;
private Stringvalue ;

public StringgetName ( ) {
returnname ;
}
public voidsetName ( Stringname ) {
this. name =name ;
}
public StringgetValue ( ) {
returnvalue ;
}
public voidsetValue ( Stringvalue ) {
this. value =value ;
}
}

Response.java

public classResponse {
private HttpURLConnectioncon = null ;

publicResponse ( ) { }

publicResponse ( HttpURLConnectioncon ) {
this. con =con ;
}

/**
* 获取数据
*/

publicList <Student >getObjectList ( ) {
InputStreamis ;
List <Student >stus = null ;
try {
is =con. getInputStream ( ) ;
ObjectInputStreamois = new ObjectInputStream (is ) ;
stus = (List <Student > )ois. readObject ( ) ;
} catch ( IOExceptione ) {
e. printStackTrace ( ) ;
} catch ( ClassNotFoundExceptione ) {
e. printStackTrace ( ) ;
}
returnstus ;
}
}

Student.java

public classStudent implementsjava. io. Serializable, Comparable {
private static final longserialVersionUID =1L ;

public intcompareTo ( Objecto ) {
// TODO Auto-generated method stub
return 0 ;
}

private Stringname ;
private intage ;

public StringgetName ( ) {
returnname ;
}

public voidsetName ( Stringname ) {
this. name =name ;
}

public intgetAge ( ) {
returnage ;
}

public voidsetAge ( intage ) {
this. age =age ;
}

@Override
public StringtoString ( ) {
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 = newStudent ( ) ;
student. setName ( "huyang" ) ;
student. setAge ( 24 ) ;
Student student1 = newStudent ( ) ;
student1. setName ( "the5fire" ) ;
student1. setAge ( 21 ) ;
List <Student >list = newArrayList <Student > ( 2 ) ;
list. add (student ) ;

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

最终结果展示:

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

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

更多相关文章

  1. [置顶] Android之场景桌面(一)
  2. Glide源码解析篇之框架主体结构(一)
  3. Android(安卓)Apk瘦身指南大全
  4. Android测试之旅之JUnit(一)
  5. [置顶] 浅析android中的权限管理--用户安装的apk的uid,gid是如何
  6. 包括后台的Android美食APP项目开源代码,androidapp
  7. (原)android的JNI中使用C++的类
  8. 用Carbide C++ UI Designer做UI的爽与不爽
  9. [转]编写高效的Android代码

随机推荐

  1. 关于setVisibility的几个常量
  2. Android的Lifecycle
  3. Android(安卓)SdkVersion区别及获取版本
  4. 【学习清单】我的Android学习清单
  5. Android上执行python脚本-QPython
  6. Android即时通讯——融云——基本环境搭
  7. Android(安卓)获取View的高度和宽度
  8. 开源中国-android客户端源代码阅读1
  9. Android(安卓)EditTextView 设置输入英文
  10. Android(安卓)Source Code