.Net程序员玩转Android开发---(14)客户端与服务器进行通信

      前几天看到有同学问, android客户端怎么和服务端进行数据通信,获取服务器端的数据,和服务器端进行交互,这一节我们来共同学习一下这方面的内容。首先要明白既然远程通信操作,就要有服务器端和客户端。服务器端创建服务,客户端调用服务。正如在.NET中,通常我们用WCF创建服务,客户端通过添加服务来调用.

     Android中,客户端通过向服务器端POST 数据,可以与服务器端进行交互。可以使用android中的HttpPost类来操作。

     下面我们具体演示下。这节我们服务器端采用WCF服务。

      1. 服务端

            首先我们创建WCF服务项目,我们创建resrful格式的WCF服务,这样方便接受客户端传来的数据,同时也方便调用。

             下面的代码中创建一个GetResponse接口,数据传输方式采用JSON格式进行传输,

  [ServiceContract]
    public interface IService1
    {
        [OperationContract]
        [WebInvoke(UriTemplate = "GetResponse", Method = "POST", RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Json)]
        TopResponse GetResponse(Stream stream);

        // TODO: 在此添加您的服务操作
    }


    public class TopResponse
    {
        public string ErrorCode { get; set; }

        public string ErrorMsg { get; set; }
    
    }

      

 public class Service1 : IService1
    {
        public TopResponse GetResponse(Stream stream)
        {
            TopResponse response = new TopResponse();

            StreamReader sr = new StreamReader(stream);
            string s = sr.ReadToEnd();
            sr.Dispose();
            NameValueCollection nvc = HttpUtility.ParseQueryString(s);

            if (nvc["code"] == "10000")
            {
                response.ErrorCode = "10000";
                response.ErrorMsg = "Success";
            }
            else
            {
                response.ErrorCode = "10010";
                response.ErrorMsg = "Failure";
            }

            return response;
        }
    }

  

            web.config

           

<?xml version="1.0" encoding="utf-8"?>
<configuration>

  <system.web>
    <compilation debug="true" targetFramework="4.0" />
  </system.web>

  <system.serviceModel>
    <services>
      <service name="WcfServiceDemo.Service1">
        <endpoint binding="webHttpBinding" contract="WcfServiceDemo.IService1" behaviorConfiguration="webHttp"/>
      </service>
    </services>
    <bindings>
      <webHttpBinding>
        <binding  sendTimeout="00:20:00"   maxReceivedMessageSize="2147483647" >
          <security mode="None" />
        </binding>
      </webHttpBinding>

    </bindings>
    <behaviors>
      <endpointBehaviors>
        <behavior name="webHttp">

          <webHttp/>
        </behavior>
      </endpointBehaviors>

      <serviceBehaviors>
        <behavior>
          <serviceMetadata httpGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="true"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>


    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
  
  
 <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
    <!--
        若要在调试过程中浏览 Web 应用程序根目录,请将下面的值设置为 True。
        在部署之前将该值设置为 False 可避免泄露 Web 应用程序文件夹信息。
      -->
    <directoryBrowse enabled="true"/>
  </system.webServer>

</configuration>


      2.客户端

       客户端使用httppost向服务器端post 数据,有一点要注意的是,好像在android 3.0 以后,要单独起一个线程来与服务器进行通信。

package com.example.helloword;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.os.Bundle;

public class AbsLayout extends Activity {

	
	private Thread thread;
	
	protected void onCreate(Bundle savedInstanceState) 
	{
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.abslayout);
		
		thread=new Thread(new Runnable(){
    	    @Override
            public void run()
    	    {
    	    	
    	    	try
    	    	{

    	   		 String url = "http://192.168.1.103/Service1.svc/GetResponse"; 
    	   	
    	   		 //创建连接
    	            HttpPost httpPost = new HttpPost(url); 
    	           
    	            //封装参数
    	            List<NameValuePair> params = new ArrayList<NameValuePair>(); 
    	            params.add(new BasicNameValuePair("code", "10000")); 

    	            HttpResponse httpResponse = null; 
    	            try { 
    	               
    	                httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); 
    	                httpResponse = new DefaultHttpClient().execute(httpPost); 
    	              
    	               
    	                if (httpResponse.getStatusLine().getStatusCode() == 200) { 
    	                    
    	                    String result = EntityUtils.toString(httpResponse.getEntity()); //获取返回结果 
    	                    System.out.println(result); 
    	                    
    	                
    	                } 
    	            } catch (ClientProtocolException e) { 
    	                e.printStackTrace(); 
    	            } catch (IOException e) { 
    	                e.printStackTrace(); 
    	            } 
    	    	}
    	    	catch(Exception e)
    	    	{
    	    		
    	    		e.printStackTrace();
    	    	}
    	    }
       });
		thread.start();
		
         
         
		
	}
}


      


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值