下面就几个小点做概要说明,另外,北风网的《零基础android课程》中对android平台中客户端与web服务器(课程中用到的是Tomcat)建立连接、请求网络资源的方式、大数据传输原理、断点续传等较为详细的讲解,建议你不妨购买学习。
1.android客户端和服务通信主要用http编程和socket编程
2.对于GET请求和POST请求,android平台有自己封装的AndroidHttpClient对象
3.Client和Web Server传递数据的格式一般用XML和JSON两种
4.由于和Web Server通信的过程中涉及到图片、访问Web端数据库等耗时的操作,android Client不会把这些操作放到主线程中去执行,以避免主线程阻塞、ANR等错误,当然在后台Service的中开启线程可以,但是android有自己的处理方式,handler机制、AsyncTask机制等。
5.因为你在问题中提到了“需要连接web服务器”,所以以下写两段android中的代码仅供参考:
/**
* @author shengyp
* @param urlString url地址
* @param xml 传递xml数据
* @param hashMap 设置头参数
* @return 服务器返回结果
* @throws Exception
*/
public static String sendXml(String urlString, String xml, HashMap<String, String> hashMap)
throws Exception {
byte[] data = xml.getBytes();
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setConnectTimeout(10000);
hashMap.put("Content-Type", "text/xml; charset=UTF-8");
hashMap.put("Content-Length", String.valueOf(data.length));
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
for (String key : hashMap.keySet()) {
conn.setRequestProperty(key, hashMap.get(key));
// System.out.println("key= " + key + " and value= " +
// hashMap.get(key));
}
conn.connect();
OutputStream outStream = conn.getOutputStream();
outStream.write(data);
outStream.flush();
outStream.close();
String returnXml = "";
if (conn.getResponseCode() == 200)
{
InputStream inputStream = conn.getInputStream();
BufferedReader dataInputStream = new BufferedReader(new InputStreamReader(inputStream, "utf-8"));
String line = "";
while ((line = dataInputStream.readLine()) != null) {
returnXml += line;
}
// Log.d(TAG, returnXml);
return returnXml;
}
return null;
}
/**
* 通过Httppost传递参数
*
* @param urlString 地址
* @param code 编码
* @param heads 请求
* @param xml 要传的参数
* @return
* @throws Exception
*/
public static String httpPost(String urlString, String code, HashMap<String, String> heads,
String xml) throws Exception
{
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost post = new HttpPost(urlString);
if (heads != null)
{
for (HashMap.Entry<String, String> entry : heads.entrySet())
{
post.setHeader(entry.getKey(), entry.getValue());
}
}
StringEntity entity = new StringEntity(xml, code);
post.setEntity(entity);
HttpResponse response = httpClient.execute(post);
HttpEntity httpEntity = response.getEntity();
InputStream is = httpEntity.getContent();
StringBuffer sb = new StringBuffer();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = "";
while ((line = br.readLine()) != null)
{
sb.append(line);
}
return sb.toString();
}