近期工做中项目须要开发一个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后,就能够在真机进行测试了: