废话不多说,直接入正题,供各位朋友参考~!
注意:服务器使用wcf rest风格,传递数据使用Json格式,但是并没有包装该格式,因为都是实现单参,双参必须要包装,当然单参也可以包装 ^_^
服务器端代码
wcf接口:
namespace Test { // 注意: 如果更改此处的接口名称 "IService1",也必须更新 Web.config 中对 "IService1" 的引用。 [ServiceContract] public interface IService1 { [OperationContract] [WebInvoke(UriTemplate="contact_entity",RequestFormat=WebMessageFormat.Json,ResponseFormat=WebMessageFormat.Json,Method="POST")] Person contact_entity(Person ps); [OperationContract] [WebInvoke(UriTemplate = "contact_entity_return_string", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, Method = "POST")] string contact_entity_return_string(Person ps); [OperationContract] [WebInvoke(UriTemplate = "test1", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, Method = "POST")] string test1(string pass_string); } }
wcf接口实现
namespace Test { // 注意: 如果更改此处的类名“Service1”,也必须更新 Web.config 和关联的 .svc 文件中对“Service1”的引用。 public class Service1 : IService1 { #region IService1 成员 public Person contact_entity(Person ps) { // throw new NotImplementedException(); ps.username = "successful"; return ps; } public string contact_entity_return_string(Person ps) { // throw new NotImplementedException(); if (ps.username == "jwc") { return "successful"; } else { return "failth"; } } public string test1(string pass_string) { pass_string = pass_string.Replace("{", "").Replace("}", "").Trim(); string[] arry = pass_string.Split(new char[1] { ':' }); if (arry[1] == "jwc") { return "successful"; } else { return "faith"; } } #endregion } }
Person代码:
namespace Test { [DataContract] public class Person { [DataMember] public int id { get; set; } [DataMember] public string username { get; set; } [DataMember] public string password { get; set; } } }
web.config
1 <?xml version="1.0" encoding="utf-8"?>
2 <!--
3 注意: 除了手动编辑此文件以外,
4 还可以使用 Web 管理工具来配置应用程序的设置。
5 可以使用 Visual Studio 中的“网站”->“Asp.Net 配置”选项。
6 设置和注释的完整列表在
7 machine.config.comments 中,该文件通常位于
8 \Windows\Microsoft.Net\Framework\v2.x\Config
9 -->
10 <configuration>
11
12
13 <configSections>
14 <sectionGroup name="system.web.extensions" type="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
15 <sectionGroup name="scripting" type="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
16 <section name="scriptResourceHandler" type="System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
17 <sectionGroup name="webServices" type="System.Web.Configuration.ScriptingWebServicesSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
18 <section name="jsonSerialization" type="System.Web.Configuration.ScriptingJsonSerializationSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="Everywhere" />
19 <section name="profileService" type="System.Web.Configuration.ScriptingProfileServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication" />
20 <section name="authenticationService" type="System.Web.Configuration.ScriptingAuthenticationServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication" />
21 <section name="roleService" type="System.Web.Configuration.ScriptingRoleServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication" />
22 </sectionGroup>
23 </sectionGroup>
24 </sectionGroup>
25 </configSections>
26
27
28 <appSettings/>
29 <connectionStrings/>
30
31 <system.web>
32 <!--
33 设置 compilation debug="true" ,将调试符号
34 插入已编译的页面中。但由于这会影响性能,
35 因此请只在开发过程中
36 将此值设置为 true。
37 -->
38 <compilation debug="false">
39
40 <assemblies>
41 <add assembly="System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
42 <add assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
43 </assemblies>
44
45 </compilation>
46 <!--
47 通过 <authentication> 节可以配置
48 ASP.NET 使用的安全身份验证
49 模式,以标识传入的用户。
50 -->
51 <authentication mode="Windows" />
52 <!--
53 通过 <customErrors> 节可以配置在执行请求过程中出现未处理错误时,
54 应执行的操作。
55 具体说来,开发人员通过该节
56 可以配置要显示的 html 错误页
57 以代替错误堆栈跟踪。
58
59 <customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
60 <error statusCode="403" redirect="NoAccess.htm" />
61 <error statusCode="404" redirect="FileNotFound.htm" />
62 </customErrors>
63 -->
64
65
66 <pages>
67 <controls>
68 <add tagPrefix="asp" namespace="System.Web.UI" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
69 </controls>
70 </pages>
71
72 <httpHandlers>
73 <remove verb="*" path="*.asmx"/>
74 <add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
75 <add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
76 <add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" validate="false"/>
77 </httpHandlers>
78 <httpModules>
79 <add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
80 </httpModules>
81
82
83 </system.web>
84
85 <system.codedom>
86 <compilers>
87 <compiler language="c#;cs;csharp" extension=".cs" warningLevel="4"
88 type="Microsoft.CSharp.CSharpCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
89 <providerOption name="CompilerVersion" value="v3.5"/>
90 <providerOption name="WarnAsError" value="false"/>
91 </compiler>
92 </compilers>
93 </system.codedom>
94
95 <system.web.extensions>
96 <scripting>
97 <webServices>
98 <!--
99 取消对此节的注释以启用身份验证服务。如果适用,请加入
100 requireSSL="true"。
101
102 <authenticationService enabled="true" requireSSL = "true|false"/>
103 -->
104 <!--
105 取消对这些行的注释,以启用配置文件服务并选择
106 可在 ASP.NET AJAX 应用程序中检索和修改的
107 配置文件属性。
108
109 <profileService enabled="true"
110 readAccessProperties="propertyname1,propertyname2"
111 writeAccessProperties="propertyname1,propertyname2" />
112 -->
113 <!--
114 取消对此节的注释,以启用角色服务。
115
116 <roleService enabled="true"/>
117 -->
118 </webServices>
119 <!--
120 <scriptResourceHandler enableCompression="true" enableCaching="true" />
121 -->
122 </scripting>
123 </system.web.extensions>
124 <!--
125 在 Internet 信息服务 7.0 下,运行 ASP.NET AJAX 要求
126 system.webServer 节。这在以前版本的 IIS 中并非必需。
127 -->
128 <system.webServer>
129 <validation validateIntegratedModeConfiguration="false"/>
130 <modules>
131 <add name="ScriptModule" preCondition="integratedMode" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
132 </modules>
133 <handlers>
134 <remove name="WebServiceHandlerFactory-Integrated"/>
135 <add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode"
136 type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
137 <add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode"
138 type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
139 <add name="ScriptResource" preCondition="integratedMode" verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
140 </handlers>
141 </system.webServer>
142
143
144 <system.serviceModel>
145 <services>
146 <service name="WcfService1.Service1" behaviorConfiguration="WcfService1.Service1Behavior">
147 <!-- Service Endpoints -->
148 <endpoint address="" binding="webHttpBinding" contract="WcfService1.IService1" behaviorConfiguration="webBehavior">
149 <!--
150 部署时,应删除或替换下列标识元素,以反映
151 在其下运行部署服务的标识。删除之后,WCF 将
152 自动推导相应标识。
153 -->
154 <identity>
155 <dns value="localhost"/>
156 </identity>
157 </endpoint>
158 <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
159 </service>
160 </services>
161 <behaviors>
162 <endpointBehaviors>
163 <behavior name="webBehavior">
164 <!--这里必须设置-->
165 <webHttp/>
166 </behavior>
167 </endpointBehaviors>
168 <serviceBehaviors>
169 <behavior name="WcfService1.Service1Behavior">
170 <!-- 为避免泄漏元数据信息,请在部署前将以下值设置为 false 并删除上面的元数据终结点-->
171 <serviceMetadata httpGetEnabled="true"/>
172 <!-- 要接收故障异常详细信息以进行调试,请将以下值设置为 true。在部署前设置为 false 以避免泄漏异常信息-->
173 <serviceDebug includeExceptionDetailInFaults="false"/>
174 </behavior>
175 </serviceBehaviors>
176 </behaviors>
177 </system.serviceModel>
178 </configuration>
客户端代码
public class Wcf_Json_PassActivity extends Activity { private Button invok1_btn; private Button invok2_btn; private Button invok3_btn; private EditText result_txt; private String uri1 = "http://192.168.1.229/service1.svc/contact_entity"; private String uri2 = "http://192.168.1.229/service1.svc/contact_entity_return_string"; private String uri3 = "http://192.168.1.229/service1.svc/test1"; private HttpClient hc = null; private HttpPost hp = null; private HttpResponse hr = null; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); findAll(); bind(); } public void findAll() { invok1_btn = (Button) this.findViewById(R.id.invok1_btn); invok2_btn = (Button) this.findViewById(R.id.invok2_btn); invok3_btn = (Button) this.findViewById(R.id.invok3_btn); result_txt = (EditText) this.findViewById(R.id.result_txt); } public void bind() { invok1_btn.setOnClickListener(mylistener); invok2_btn.setOnClickListener(mylistener); invok3_btn.setOnClickListener(mylistener); } Handler hd = new Handler() { @Override public void handleMessage(Message msg) { // TODO Auto-generated method stub // super.handleMessage(msg); if (msg.what == 123) { result_txt.setText(msg.obj.toString()); } } }; private View.OnClickListener mylistener = new OnClickListener() { public void onClick(View v) { // TODO Auto-generated method stub switch (v.getId()) { case R.id.invok1_btn: JSONObject jo1 = new JSONObject(); try { jo1.put("id", 11); jo1.put("username", "jwc"); jo1.put("password", "123456"); Thread th1 = new Thread(new mythread(uri1, jo1.toString())); th1.start(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } // invok_wcf(uri1,) break; case R.id.invok2_btn: JSONObject jo2 = new JSONObject(); try { jo2.put("id", 11); jo2.put("username", "jwc"); jo2.put("password", "123456"); Thread th2 = new Thread(new mythread(uri2, jo2.toString())); th2.start(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } break; case R.id.invok3_btn: JSONObject jo3 = new JSONObject(); try { jo3.put("pass_string", "jwc"); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } Thread th3 = new Thread(new mythread(uri3,jo3.toString())); th3.start(); break; } } }; class mythread implements Runnable { String my_uri; String my_date; public mythread(String uri, String date) { this.my_uri = uri; this.my_date = date; } public void run() { // TODO Auto-generated method stub hc = new DefaultHttpClient(); hp = new HttpPost(my_uri); StringEntity se; try { se = new StringEntity(my_date, HTTP.UTF_8); se.setContentType("application/json"); hp.setEntity(se); hr = hc.execute(hp); String strResp = null; if (hr.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK) { strResp = EntityUtils.toString(hr.getEntity()); } else { strResp = "$no_found_date$"; } Message msg = hd.obtainMessage(123); msg.obj = strResp; hd.sendMessage(msg); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { hp.abort(); } } } }