http://www.kwstu.com/ArticleView/kwstu_2013320125217826
最近一直在搞android开发,开发中需要用到以http post方式访问wcf服务,此文用于总结安卓端如何发送,服务端wcf(webservice)代码如何接受,传输过程以json方式传输。
有问题请联系:QQ:404926765 文章作者:kwstu
一、先看android端发送代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
String strResp =
""
;
//接受返回结果
request.setHeader(
"Accept"
,
"application/json"
);
request.setHeader(
"Content-type"
,
"application/json"
);
// 构造json
JSONStringer vehicle;
try
{
vehicle =
new
JSONStringer()
.object()
.key(
"user"
)
.object()
.key(
"UserName"
).value(
"aa444大宝aadddd"
)
.key(
"PassWord"
).value(
"54fffff444"
)
.endObject()
.endObject();
StringEntity entity =
new
StringEntity(vehicle.toString(),
"UTF-8"
);
//需要设置成utf-8否则汉字乱码
request.setEntity(entity);
// 向WCF服务发送请求
DefaultHttpClient httpClient =
new
DefaultHttpClient();
HttpResponse response = httpClient.execute(request);
// 判断是否成功
if
(response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK)
strResp = EntityUtils.toString(response.getEntity(),
"UTF-8"
);
System.out.println(
"strResp="
+strResp);
Log.d(
"WebInvoke"
,
"Saving : "
+ response.getStatusLine().getStatusCode());
}
catch
(Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Reload plate numbers
|
二、以下是wcf服务端接收代码:
服务器端接收json数据必须创建对应的类(可能还有其他方式,本人刚接触不知道)
1、对应json类:
1
2
3
4
5
6
7
|
public
class
UserType
{
[DataMember]
public
string
UserName {
get
;
set
; }
[DataMember]
public
string
PassWord {
get
;
set
; }
}
|
2、定义wcf接口:
1
2
3
|
[OperationContract]
[WebInvoke(Method =
"POST"
, UriTemplate =
"Denglutmp"
, ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)]
string
Denglutmp(UserType user);
|
3、实现接口:
1
2
3
4
5
|
public
string Denglutmp(UserType user)
{
//你的处理方法,本方法将客户端传过来的数据之间返回
return
user.UserName+ user.PassWord;
}
|
所属分类:
Android