WCF服务端与使用HttpURLConnection的Android客户端简单示例
来源:互联网 发布:python使用手册 编辑:程序博客网 时间:2024/05/18 00:45
WCF服务端
契约Contract
using System.ServiceModel;using System.ServiceModel.Web;namespace Contract{ /// <summary> /// Android客户端调用的服务接口 /// </summary> [ServiceContract(Name = "WcfService", Namespace = "http://tempuri.org/")] public interface IWcfService { /// <summary> /// 客户端访问 url + /TestGet /// </summary> /// <returns></returns> [OperationContract] [WebGet( ResponseFormat = WebMessageFormat.Json)] //默认XML格式 string TestGet(); /// <summary> /// 客户端访问 url + /TestGet1?name=zhangsan /// </summary> /// <param name="name"></param> /// <returns></returns> [OperationContract] [WebGet( RequestFormat = WebMessageFormat.Json, //json或xml无影响 ResponseFormat = WebMessageFormat.Json)] string TestGet1(string name); /// <summary> /// 客户端访问 url + /TestGet2?name=zhangsan&age=20 /// </summary> /// <param name="name"></param> /// <param name="age"></param> /// <returns></returns> [OperationContract] [WebGet( RequestFormat = WebMessageFormat.Json, //json或xml无影响 ResponseFormat = WebMessageFormat.Json)] string TestGet2(string name, int age); /// <summary> /// 客户端访问: /// GET or POST:url + /TestGetOrPost /// </summary> /// <returns></returns> [OperationContract] [WebInvoke( Method = "*", ResponseFormat = WebMessageFormat.Json)] string TestGetOrPost(); /// <summary> /// 客户端访问: /// GET or POST:url + /TestGetOrPost1/URLEncoder.encode(json, "utf8") /// </summary> /// <param name="json"></param> /// <returns></returns> [OperationContract] [WebInvoke( Method = "*", //*既可以POST也可以GET UriTemplate = "TestGetOrPost1/{json}", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)] string TestGetOrPost1(string json); }}
服务Service
using Contract;using Newtonsoft.Json.Linq;using System;namespace Service{ public class WcfService : IWcfService { public string TestGet() { Console.WriteLine(); Console.WriteLine("TestGet()"); //通知移动端接收成功 return "{\"result\":1}"; } public string TestGet1(string name) { Console.WriteLine(); Console.WriteLine("TestGet1(name)"); Console.WriteLine("name = " + name); //通知移动端接收成功 return "{\"result\":1}"; } public string TestGet2(string name, int age) { Console.WriteLine(); Console.WriteLine("TestGet2(name, age)"); Console.WriteLine("name = " + name + " , age = " + age); //通知移动端接收成功 return "{\"result\":1}"; } public string TestGetOrPost() { Console.WriteLine(); Console.WriteLine("TestGetOrPost()"); //通知移动端接收成功 return "{\"result\":1}"; } public string TestGetOrPost1(string json) { Console.WriteLine(); Console.WriteLine("TestGetOrPost1(json)"); JObject obj = JsonHelper.ReadJson(json); if (obj == null) { return "{\"result\":0}"; } Console.WriteLine(); Console.WriteLine(obj.ToString()); string name = JObjectReader.GetName(obj); int? age = JObjectReader.GetAge(obj); if (string.IsNullOrEmpty(name) || age.HasValue == false) { return MsgResult.FailureOfErrorParam(); } return "{\"name\":\"" + name + "\", \"age\":" + age + "}"; } }}
控制台程序Hosting
App.config
<?xml version="1.0" encoding="utf-8"?><configuration> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/> </startup> <system.serviceModel> <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/> <behaviors> <endpointBehaviors> <behavior name="webHttpBehavior"> <webHttp helpEnabled="true"/> </behavior> </endpointBehaviors> <serviceBehaviors> <behavior name="webHttpBehavior"> <serviceMetadata httpGetEnabled="true" httpGetUrl="metadata"/> <serviceDebug includeExceptionDetailInFaults="true"/> <dataContractSerializer maxItemsInObjectGraph="2147483647"/> </behavior> </serviceBehaviors> </behaviors> <bindings> <webHttpBinding> <binding name="webHttpBinding" maxBufferSize="2147483647" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647"> <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647"/> </binding> </webHttpBinding> </bindings> <services> <service behaviorConfiguration="webHttpBehavior" name="Service.WcfService"> <endpoint address="/" behaviorConfiguration="webHttpBehavior" binding="webHttpBinding" bindingConfiguration="webHttpBinding" name="WcfService" contract="Contract.IWcfService" /> <host> <baseAddresses> <add baseAddress="http://localhost:8888/service" /> </baseAddresses> </host> </service> </services> </system.serviceModel> <system.webServer> <modules runAllManagedModulesForAllRequests="true"/> </system.webServer> <!--保存具体的错误信息到svclog文件中--> <system.diagnostics> <sources> <source name="System.ServiceModel" switchValue="Warning" propagateActivity="true"> <listeners> <add name="xml" /> </listeners> </source> </sources> <sharedListeners> <add name="xml" type="System.Diagnostics.XmlWriterTraceListener" initializeData="F:\wcf.svclog" /> </sharedListeners> </system.diagnostics></configuration>
Program.cs
using System;using System.ServiceModel;using Service;namespace Hosting{ class Program { static void Main(string[] args) { Console.WriteLine("---------------------------------------------------------------"); ServiceHost host = null; try { host = new ServiceHost(typeof(Service.WcfService)); host.Opened += host_Opened; host.Open(); Console.WriteLine("按任意键终止服务!"); } catch (Exception ex) { Console.WriteLine(ex.Message); } finally { Console.Read(); if (host != null) { host.Close(); host = null; } } } static void host_Opened(object sender, EventArgs e) { Console.WriteLine("Service已经启动"); } }}
Android客户端
MainActivity.java
import android.app.Activity;import android.os.Handler;import android.os.Bundle;import android.widget.TextView;public class MainActivity extends Activity { private Handler handler = new Handler(); private TextView textView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = (TextView) findViewById(R.id.text); new HttpURLConnectionThread(textView, handler).start(); }}
HttpURLConnectionThread.java
import android.os.Handler;import android.widget.TextView;import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.client.methods.HttpPost;import org.apache.http.impl.client.DefaultHttpClient;import org.json.JSONException;import org.json.JSONStringer;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.OutputStream;import java.io.UnsupportedEncodingException;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;import java.net.URLDecoder;import java.net.URLEncoder;public class HttpURLConnectionThread extends Thread { private TextView textView; private Handler handler; public HttpURLConnectionThread (TextView textView, Handler handler) { this.textView = textView; this.handler = handler; } @Override public void run() { // doGet("http://www.imooc.com/api/teacher?type=4&num=30"); //网络服务// doGet("http://192.168.1.222:8888/service/TestGet"); //本地服务:无参数// doGet("http://192.168.1.222:8888/service/TestGet2?name=zhangsan&age=20"); //本地服务:两个参数 try { doGet("http://192.168.1.222:8888/service/TestGet2?name="+URLEncoder.encode("张三", "utf-8")+"&age=20"); //本地服务:两个参数(带中文) } catch (UnsupportedEncodingException e) { e.printStackTrace(); }// doGet("http://192.168.1.222:8888/service/TestGetOrPost"); //本地服务:无参数// doPost("http://192.168.1.222:8888/service/TestGetOrPost", ""); //本地服务,无参数// try {// JSONStringer json = new JSONStringer()// .object()// .key("name").value("zhangsan")// .key("age").value(28)// .endObject();// doGet("http://192.168.1.222:8888/service/TestGetOrPost1/" //本地服务,一个参数// + URLEncoder.encode(json.toString(), "utf8"));// doPost("http://172.16.24.253:8888/service/TestGetOrPost1/" + URLEncoder.encode(json.toString(), "utf8"), ""); //本地服务,一个参数// } catch (JSONException e) {// e.printStackTrace();// } catch (UnsupportedEncodingException e) {// e.printStackTrace();// } } private void doPost(String url, String json) { try { URL httpUrl = new URL(url); HttpURLConnection connection = (HttpURLConnection) httpUrl.openConnection(); connection.setRequestMethod("POST"); connection.setDoOutput(true); connection.setReadTimeout(5000); OutputStream outputStream = connection.getOutputStream(); outputStream.write(json.getBytes()); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); StringBuilder sb = new StringBuilder(); String str; while ((str = reader.readLine()) != null) { sb.append(str); } final String result = sb.toString(); handler.post(new Runnable() { @Override public void run() { textView.setText(result); } }); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } private void doGet(String url) { try { URL httpUrl = new URL(url); HttpURLConnection connection = (HttpURLConnection) httpUrl.openConnection(); connection.setRequestMethod("GET"); connection.setReadTimeout(5000); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); StringBuilder sb = new StringBuilder(); String str; while ((str=reader.readLine())!=null) { sb.append(str); } final String result = sb.toString(); handler.post(new Runnable() { @Override public void run() { textView.setText(result); } }); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }}
0 0
- WCF服务端与使用HttpURLConnection的Android客户端简单示例
- WCF服务端与使用HttpClient的Android客户端简单示例
- WCF服务端与客户端代码示例
- Android客户端使用HttpURLConnection doGet与服务器数据交互简单示例
- C# 编写WCF简单的服务端与客户端
- WCF服务端与客户端
- 使用简单的ServiceSockt实现服务端与客户端的通信
- Android HttpURLConnection的简单使用
- 使用CXF编写简单客户端与服务端
- WCF客户端与服务端之间建立通信的几个要点
- 简单的服务端与客户端通信代码
- SVN的简单使用(服务端+客户端)
- 一个简单的UDP服务端和客户端示例
- 一个简单的UDP服务端和客户端示例
- 基于Python的TCP服务端/客户端简单应用示例
- Android客户端与服务端交互之登陆示例
- Android客户端与服务端交互之登陆示例
- Android客户端与服务端交互之登陆示例
- The connection to adb is down, and a severe error has occured.
- 如何给物体添加阴影效果
- 函数形参和实参特点
- 性能测试步骤及分析
- C++ 文件名和 路径
- WCF服务端与使用HttpURLConnection的Android客户端简单示例
- Android Studio设置注释模板
- Internet Printing Protocol/1.1: Encoding and Transport 前三章翻译
- 在VS2010的环境下,给mfc下的对话框添加启动画面
- NYOJ 585 取石子(六)(尼姆博奕)
- github 创建项目流程
- strcpy函数详解
- 如何把一个已有的ADT项目,导入到当前的ADT中
- AutoIT使用总结一