近期工做中項目須要開發一個Android客戶端,調用WCF服務獲取數據。我以前沒有作過Android上的Web Service開發,臨時查了一下,整理出一個完整的例子,備忘。html
測試代碼下載java
一、建立一個WCF服務項目:android
二、添加一個很簡單的方法,輸出一個字符串:web
注意UriTemplate 的寫法,多個參數依此類推。BodyStyle 指定爲容許多個參數,數據格式使用移動終端友好的Json格式,XML數據冗餘性太大。apache
三、修改 web.configjson
使用webHttpBinding 針對於 Restful Web Service,若使用basicHttpBinding則針對於 SOAP Web Service。瀏覽器
四、編譯成功後,使用VS 發佈到IIS中:app
先在IIS中創建一個網站:異步
而後發佈到該網站中:ide
發佈成功後,在瀏覽器中查看WCF服務確認發佈成功:
五、下面開始開發Android客戶端測試程序,在Eclipse中建立一個Android項目:
六、就放置一個按鈕,點擊按鈕時調用WCF服務:
七、若調用成功,記錄一條日誌:
package com.brooks.wcfdemo;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public void WCFTestLinstener(View view)
{
new Thread(WCFTest).start();
}
Runnable WCFTest = new Runnable(){
public void run() {
// TODO Auto-generated method stub
CallWCF();
}
};
private void CallWCF() {
try {
// Send GET request to <service>/GetPlates
HttpGet request = new HttpGet("http://192.168.0.100:90/AndroidService.svc/fnTest/WCF");
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(request);
HttpEntity responseEntity = response.getEntity();
Log.d("WCF", retrieveInputStream(responseEntity));
} catch (Exception e) {
e.printStackTrace();
}
}
protected String retrieveInputStream(HttpEntity httpEntity) {
int length = (int) httpEntity.getContentLength();
if (length < 0)
length = 10000;
StringBuffer stringBuffer = new StringBuffer(length);
try {
InputStreamReader inputStreamReader = new InputStreamReader(
httpEntity.getContent(), HTTP.UTF_8);
char buffer[] = new char[length];
int count;
while ((count = inputStreamReader.read(buffer, 0, length - 1)) > 0) {
stringBuffer.append(buffer, 0, count);
}
} catch (UnsupportedEncodingException e) {
} catch (IllegalStateException e) {
} catch (IOException e) {
}
return stringBuffer.toString();
}
}
由於Android 高版本對主線程上的操做作了限制,故須要異步調用。
首先使用模擬器測試:
手機開啓Wifi後,就能夠在真機進行測試了: