下面就幾個小點作概要說明,另外,北風網的《零基礎android課程》中對android平臺中客戶端與web服務器(課程中用到的是Tomcat)創建鏈接、請求網絡資源的方式、大數據傳輸原理、斷點續傳等較爲詳細的講解,建議你不妨購買學習。 android
1.android客戶端和服務通訊主要用http編程和socket編程 web
2.對於GET請求和POST請求,android平臺有本身封裝的AndroidHttpClient對象,關於HttpClient的有關信息如下我附上一個連接 數據庫
http://blog.csdn.net/hzh839900/article/details/6061272 編程
3.Client和Web Server傳遞數據的格式通常用XML和JSON兩種 服務器
4.因爲和Web Server通訊的過程當中涉及到圖片、訪問Web端數據庫等耗時的操做,android Client不會把這些操做放到主線程中去執行,以免主線程阻塞、ANR等錯誤,固然在後臺Service的中開啓線程能夠,可是android有本身的處理方式,handler機制、AsyncTask機制等。 網絡
5.由於你在問題中提到了「須要鏈接web服務器」,因此如下寫兩段android中的代碼僅供參考: app
/**
* @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();
} socket