android与服务端通信

                          Android与服务器通信

Android与服务器通信大致分为2种,一种是http形式,一种是socket形式。下面我分别介绍这2种方法。

1、 http形式

   服务器端建立:

android与服务端通信_第1张图片

EncodingFilter.java代码如下:

package com.example;

 

import java.io.IOException;

import javax.servlet.Filter;

import javax.servlet.FilterChain;

import javax.servlet.FilterConfig;

import javax.servlet.ServletException;

import javax.servlet.ServletRequest;

import javax.servlet.ServletResponse;

import javax.servlet.http.HttpServletRequest;

 

/**

 * Servlet Filter implementation class EncodingFilter

 */

public class EncodingFilter implements Filter {

 

    /**

     * Default constructor.

     */

    public EncodingFilter() {

      

    }

 

 /**

  * @see Filter#destroy()

  */

 public void destroy() {

 

 }

 

 /**

  * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)

  */

 public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

  HttpServletRequest req = (HttpServletRequest) request;

 

  if("GET".equals(req.getMethod())){

   EncodingHttpServletRequest  wrapper = new EncodingHttpServletRequest(req);

   chain.doFilter(wrapper, response);

  } else {//post

   req.setCharacterEncoding("UTF-8");

   chain.doFilter(request, response);

  }

 

 

 }

 

 /**

  * @see Filter#init(FilterConfig)

  */

 public void init(FilterConfig fConfig) throws ServletException {

 

 }

 

}

 

EncodingHttpServletRequest.java代码如下:

package com.example;

import java.io.UnsupportedEncodingException;

 

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletRequestWrapper;

 

public class EncodingHttpServletRequest extends HttpServletRequestWrapper {

 

 private HttpServletRequest request;

 public EncodingHttpServletRequest(HttpServletRequest request) {

  super(request);

  this.request = request;

 }

 @Override

 public String getParameter(String name) {

  String value = request.getParameter(name);

  if(value!=null){

   try {

    value = new String(value.getBytes("ISO8859-1"),"UTF-8");

   } catch (UnsupportedEncodingException e) {

   

    e.printStackTrace();

   }

  }

  return value;

 }

 

 

}

 

Servlet.java代码如下

package com.example;

 

import java.io.IOException;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import com.example.EncodingHttpServletRequest;

 

/**

 * Servlet implementation class ManageServlet

 */

public class servlet extends HttpServlet {

 private static final long serialVersionUID = 1L;

      

    /**

     * @see HttpServlet#HttpServlet()

     */

    public servlet() {

        super();

    }

 

 /**

  * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)

  */

 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

  String title = request.getParameter("title");

 

  EncodingHttpServletRequest requsete = new EncodingHttpServletRequest(request);

  String titlee = requsete.getParameter("title");

 

  //把客户端传递过来的参数进行重新编码使之能支持中文

  title = new String(title.getBytes("GB2312"),"UTF-8");//使用过滤器后就不需要每次都要进行此操作

  String timelength = request.getParameter("timelength");

  System.out.println("视频名称:"+titlee);

  System.out.println("播放时长:"+timelength);

 }

 

 /**

  * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)

  */

 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

  String title = request.getParameter("title");

  //把客户端传递过来的参数进行重新编码使之能支持中文

  title = new String(title.getBytes("GB2312"),"UTF-8");//使用过滤器后就不需要每次都要进行此操作

  String timelength = request.getParameter("timelength");

  System.out.println("视频名称:"+title);

  System.out.println("播放时长:"+timelength);

 }

 

}

 

既然有servlet就不得不在web.xml中配置一下了

<servlet>

   <servlet-name>servlet</servlet-name>

   <servlet-class>com.example.servlet</servlet-class>

 </servlet>

 <servlet-mapping>

   <servlet-name>servlet</servlet-name>

   <url-pattern>/servlet</url-pattern>

  </servlet-mapping>

 

进行通信是必须先把服务器打开,所以先把servlettomcat打开,

http://localhost:8080/http_service/servlet

 

服务器设置好了,再开发android客户端。

android与服务端通信_第2张图片

Http_androidActivity.java代码

package com.example.newsmanage;

 

import android.app.Activity;

import android.os.Bundle;

 

public class Http_androidActivity extends Activity {

    /** Called when the activity is first created. */

    @Override

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);

    }

}

NewsManageActivity.java代码

package com.example.newsmanage;

 

import com.example.service.NewsService;

 

import android.app.Activity;

import android.os.Bundle;

import android.view.View;

import android.widget.Button;

import android.widget.EditText;

import android.widget.Toast;

 

public class NewsManageActivity extends Activity {

    /** Called when the activity is first created. */

 

 EditText titleText;

 EditText lengthText;

 Button button;

    @Override

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);

       

        titleText = (EditText) this.findViewById(R.id.title);

        lengthText = (EditText) this.findViewById(R.id.timelength);

       

        button = (Button) this.findViewById(R.id.button);

       

    }

   

    public void save(View v) throws Exception{

     String title = titleText.getText().toString();

     String timelength = lengthText.getText().toString();

     boolean result = NewsService.save(title,timelength);

     if(result){

      Toast.makeText(getApplicationContext(), R.string.success, Toast.LENGTH_LONG).show();

     } else {

      Toast.makeText(getApplicationContext(), R.string.fail, Toast.LENGTH_LONG).show();

     }

    }

}

NewsService.java代码

package com.example.service;

 

import java.io.OutputStream;

import java.net.HttpURLConnection;

import java.net.URL;

import java.net.URLEncoder;

import java.util.ArrayList;

import java.util.HashMap;

import java.util.List;

import java.util.Map;

 

import org.apache.http.HttpResponse;

import org.apache.http.NameValuePair;

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;

 

public class NewsService {

 

 /**

  * 保存数据,传递参数给web服务器端

  * @param title 标题

  * @param timelength 时长

  * @return

  */

 public static boolean save(String title, String timelength) throws Exception {

  //119.119.228.5为本机IP地址,不能用localhost代替

  String path = "http://192.168.1.5:8080/http_service/servlet";

  Map<String,String> params = new HashMap<String,String>();

  params.put("title", title);

  params.put("timelength", timelength);

  //get请求方式

  return sendGETRequest(path,params,"UTF-8");

  //post请求方式

  //return sendPOSTRequest(path,params,"UTF-8");

  //httpClient请求方式,如果单纯传递参数的话建议使用GET或者POST请求方式

  //return sendHttpClientPOSTRequest(path,params,"UTF-8");//httpclient已经集成在android

 }

 

 /**

  * 通过HttpClient发送post请求

  * @param path

  * @param params

  * @param encoding

  * @return

  * @throws Exception

  */

 private static boolean sendHttpClientPOSTRequest(String path,

   Map<String, String> params, String encoding) throws Exception {

  List<NameValuePair> pairs = new ArrayList<NameValuePair>();//存放请求参数

 

  for(Map.Entry<String, String> entry:params.entrySet()){

   pairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));

  }

  //防止客户端传递过去的参数发生乱码,需要对此重新编码成UTF-8

  UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairs,encoding);

  HttpPost httpPost = new HttpPost(path);

  httpPost.setEntity(entity);

  DefaultHttpClient client = new DefaultHttpClient();

  HttpResponse response = client.execute(httpPost);

  if(response.getStatusLine().getStatusCode() == 200){

   return true;

  }

 

  return false;

 }

 

 /**

  * 放松post请求

  * @param path 请求路径

  * @param params 请求参数

  * @param encoding 编码

  * @return 请求是否成功

  */

 private static boolean sendPOSTRequest(String path,

   Map<String, String> params, String encoding) throws Exception{

  StringBuilder data = new StringBuilder(path);

  for(Map.Entry<String, String> entry:params.entrySet()){

  data.append(entry.getKey()).append("=");

   //防止客户端传递过去的参数发生乱码,需要对此重新编码成UTF-8

  data.append(URLEncoder.encode(entry.getValue(),encoding));

   data.append("&");

  }

 

  data.deleteCharAt(data.length() - 1);

 

  byte[] entity = data.toString().getBytes();//得到实体数据

  HttpURLConnection conn = (HttpURLConnection) new URL(path).openConnection();

  conn.setConnectTimeout(5000);

  conn.setRequestMethod("POST");

 

  conn.setDoOutput(true);//设置为允许对外输出数据

 

 conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

 conn.setRequestProperty("Content-Length", String.valueOf(entity.length));

 

  OutputStream outStream = conn.getOutputStream();

  outStream.write(entity);//写到缓存

 

  if(conn.getResponseCode()==200){//只有取得服务器返回的http协议的任何一个属性时才能把请求发送出去

   return true;

  }

 

  return false;

 }

 

 /**

  * 发送GET请求

  * @param path 请求路径

  * @param params 请求参数

  * @return 请求是否成功

  * @throws Exception

  */

 private static boolean sendGETRequest(String path,

   Map<String, String> params,String encoding) throws Exception {

  StringBuilder url = new StringBuilder(path);

  url.append("?");

  for(Map.Entry<String, String> entry:params.entrySet()){

  url.append(entry.getKey()).append("=");

   //get方式请求参数时对参数进行utf-8编码,URLEncoder

   //防止客户端传递过去的参数发生乱码,需要对此重新编码成UTF-8

  url.append(URLEncoder.encode(entry.getValue(), encoding));

   url.append("&");

  }

  url.deleteCharAt(url.length()-1);

  HttpURLConnection conn = (HttpURLConnection) new URL(url.toString()).openConnection();

  conn.setConnectTimeout(5000);

  conn.setRequestMethod("GET");

  if(conn.getResponseCode() == 200){

   return true;

  }

  return false;

 }

 

}

 

Main.xml代码如下

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

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="fill_parent"

    android:layout_height="fill_parent"

    android:orientation="vertical" >

 

   <TextView

        android:layout_width="fill_parent"

        android:layout_height="wrap_content"

        android:text="@string/title" />

 

   <EditText

        android:id="@+id/title"

        android:layout_width="fill_parent"

        android:layout_height="wrap_content" >

 

        <requestFocus />

   </EditText>

 

   <TextView

        android:id="@+id/textView1"

        android:layout_width="fill_parent"

        android:layout_height="wrap_content"

        android:text="@string/timelength" />

 

   <EditText

        android:id="@+id/timelength"

        android:layout_width="fill_parent"

        android:layout_height="wrap_content" android:numeric="integer"/>

 

   <Button

        android:id="@+id/button"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="@string/button" android:onClick="save"/>

 

</LinearLayout>

 

AndroidManifest.xml代码如下

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

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

    package="com.example.newsmanage"

    android:versionCode="1"

    android:versionName="1.0" >

 

   <uses-sdk android:minSdkVersion="7" />

 

   <application

        android:icon="@drawable/ic_launcher"

        android:label="@string/app_name" >

        <activity

           android:name=".NewsManageActivity"

           android:label="@string/app_name" >

            <intent-filter>

                <action android:name="android.intent.action.MAIN" />

 

                <category android:name="android.intent.category.LAUNCHER" />

            </intent-filter>

        </activity>

   </application>

 <uses-permission android:name="android.permission.INTERNET"/>

   

</manifest>

 

开发好后就开始测试吧,先运行android客户端,这里服务器端不接收中文的,你可以设置一下编码格式的。

android与服务端通信_第3张图片

点击发送,在服务器端就会接收到发送过来的信息

android与服务端通信_第4张图片

测试成功。

 

2、 现在开发socket案例

服务器端比较简单,只要建一个java文件就可以了,一直运行着就可以了。

 

socket_service.java

package example;

 

 

import java.io.BufferedReader; 

import java.io.BufferedWriter; 

import java.io.InputStreamReader; 

import java.io.OutputStreamWriter; 

import java.io.PrintWriter;  

import java.net.ServerSocket; 

import java.net.Socket; 

 

public class socket_service implements Runnable 

{  

    public void run() 

    { 

       try 

        { 

            //创建ServerSocket 

            ServerSocket serverSocket = new ServerSocket(54321); 

            while (true) 

            { 

               //接受客户端请求 

               Socket client = serverSocket.accept(); 

               System.out.println("accept"); 

                try 

                { 

                    //接收客户端消息 

                   BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));

                  

                  System.out.print("\n");

                   String str = in.readLine(); 

                  System.out.println("read:" + str);   

                    //向服务器发送消息 

                   PrintWriter out = new PrintWriter( new BufferedWriter( new OutputStreamWriter(client.getOutputStream())),true);       

                    out.println("server ");  

                   //关闭流 

                   out.close();  

                   in.close(); 

               } 

                catch (Exception e) 

                { 

                   System.out.println(e.getMessage()); 

                    e.printStackTrace(); 

                } 

                finally 

                { 

                    //关闭 

                   client.close(); 

                   System.out.println("close"); 

               } 

            } 

       }  

       catch (Exception e) 

        { 

           System.out.println(e.getMessage()); 

       } 

    } 

    //main函数,开启服务器 

   public static void main(String args[]) 

   { 

        Thread desktopServerThread = new Thread(new socket_service()); 

       desktopServerThread.start(); 

  } 

}

 

 

Android客户端

android与服务端通信_第5张图片

Activity01.java代码

package com.example.socket;

 

import java.io.BufferedReader; 

import java.io.BufferedWriter; 

import java.io.InputStreamReader; 

import java.io.OutputStreamWriter; 

import java.io.PrintWriter; 

import java.net.Socket; 

 

import android.app.Activity; 

import android.os.Bundle; 

import android.util.Log; 

import android.view.View; 

import android.view.View.OnClickListener; 

import android.widget.Button; 

import android.widget.EditText; 

import android.widget.TextView; 

 

public class Activity01 extends Activity 

{ 

    private final String        DEBUG_TAG   = "Activity01"; 

    

   private TextView    mTextView = null; 

    private EditText    mEditText = null; 

    private Button      mButton = null; 

    /** Called when the activity is first created. */ 

   @Override 

   public void onCreate(Bundle savedInstanceState) 

    { 

       super.onCreate(savedInstanceState); 

      setContentView(R.layout.main); 

        

       mButton = (Button)findViewById(R.id.Button01); 

       mTextView = (TextView)findViewById(R.id.TextView01); 

        mEditText = (EditText)findViewById(R.id.EditText01); 

         

        //登陆 

        mButton.setOnClickListener(new OnClickListener() 

       { 

           public void onClick(View v) 

           { 

               Socket socket = null; 

               String message = mEditText.getText().toString() + "/r/n";  

                try  

               {    

                   //创建Socket 

                  socket = new Socket("192.168.1.2",54321);  

                    //socket = new Socket("10.14.114.127",54321); //IP10.14.114.127,端口54321 

                   //向服务器发送消息 

                   PrintWriter out = new PrintWriter( new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())),true);       

                  out.println(message+"wmy");  

                     

                   //接收来自服务器的消息 

                   BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));  

                   String msg = br.readLine();  

                     

                   if ( msg != null ) 

                   { 

                      mTextView.setText(msg); 

                 } 

                    else 

                  { 

                        mTextView.setText("数据错误!"); 

                    } 

                    //关闭流 

                   out.close(); 

                    br.close(); 

                    //关闭Socket 

                    socket.close();  

               } 

              catch (Exception e)  

               { 

                   // TODO: handle exception 

                  Log.e(DEBUG_TAG, e.toString()); 

               } 

            } 

       }); 

   } 

} 

 

Socket_androidActivity.java代码

package com.example.socket;

 

import android.app.Activity;

import android.os.Bundle;

 

public class Socket_androidActivity extends Activity {

    /** Called when the activity is first created. */

    @Override

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);

    }

}

 

Main.xml代码

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

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 

    android:orientation="vertical" 

    android:layout_width="fill_parent" 

    android:layout_height="fill_parent" 

    > 

   <TextView   

    android:id="@+id/TextView01"  

    android:layout_width="fill_parent"  

    android:layout_height="wrap_content"  

    android:text="杩欓噷鏄剧ず鎺ユ敹鍒版湇鍔櫒鍙戞潵鐨勪俊鎭 

    /> 

    <EditText  

    android:id="@+id/EditText01"  

    android:text="杈撳叆瑕佸彂閫佺殑鍐呭"  

    android:layout_width="fill_parent"  

    android:layout_height="wrap_content"> 

   </EditText> 

   <Button  

    android:id="@+id/Button01" 

    android:layout_width="fill_parent" 

    android:layout_height="wrap_content" 

    android:text="鍙戦" 

    />   

</LinearLayout> 

 

AndroidManifest.xml

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

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

    package="com.example.socket"

    android:versionCode="1"

    android:versionName="1.0" >

 

   <uses-sdk android:minSdkVersion="7" />

 

   <application

        android:icon="@drawable/ic_launcher"

        android:label="@string/app_name" >

        <activity

           android:name=".Activity01"

           android:label="@string/app_name" >

            <intent-filter>

                <action android:name="android.intent.action.MAIN" />

 

                <category android:name="android.intent.category.LAUNCHER" />

            </intent-filter>

        </activity>

   </application>

 <uses-permission android:name="android.permission.INTERNET"></uses-permission>

</manifest>

 

开发好了就行测试吧

android与服务端通信_第6张图片

前后对比一下

 

android与服务端通信_第7张图片

 

服务器端:

希望对大家有用

你可能感兴趣的:(android,http,通信,socket)