近期工作中項目需要開發一個Android客戶端,調用WCF服務獲取數據。我之前沒有做過Android上的Web Service開發,臨時查了一下,整理出一個完整的例子,備忘。
1、創建一個WCF服務項目:
2、添加一個很簡單的方法,輸出一個字符串:
注意UriTemplate 的寫法,多個參數依此類推。BodyStyle 指定為允許多個參數,數據格式使用移動終端友好的Json格式,XML數據冗余性太大。
3、修改 web.config
使用webHttpBinding 針對於 Restful Web Service,若使用basicHttpBinding則針對於 SOAP Web Service。
4、編譯成功后,使用VS 發布到IIS中:
先在IIS中建立一個網站:
然后發布到該網站中:
發布成功后,在瀏覽器中查看WCF服務確認發布成功:
5、下面開始開發Android客戶端測試程序,在Eclipse中創建一個Android項目:
6、就放置一個按鈕,點擊按鈕時調用WCF服務:
7、若調用成功,記錄一條日志:
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后,就可以在真機進行測試了: