首页 > 代码库 > 【Android笔记】Android与服务器通信 http和socket两种形式

【Android笔记】Android与服务器通信 http和socket两种形式

1、 http形式

   服务器端建立:

EncodingFilter.java代码如下:

 1 package com.example; 2  3 import java.io.IOException; 4  5 import javax.servlet.Filter; 6  7 import javax.servlet.FilterChain; 8  9 import javax.servlet.FilterConfig;10 11 import javax.servlet.ServletException;12 13 import javax.servlet.ServletRequest;14 15 import javax.servlet.ServletResponse;16 17 import javax.servlet.http.HttpServletRequest;18 19 /**20 21  * Servlet Filter implementation class EncodingFilter22 23  */24 25 public class EncodingFilter implements Filter {26     /**27 28      * Default constructor.29 30      */31 32     public EncodingFilter() {33 34      35     }36 37  /**38 39   * @see Filter#destroy()40 41   */42 43  public void destroy() {44 45  }46 47  48  /**49 50   * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)51 52   */53 54  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {55 56   HttpServletRequest req = (HttpServletRequest) request;57 58  59 60   if("GET".equals(req.getMethod())){61 62    EncodingHttpServletRequest  wrapper = new EncodingHttpServletRequest(req);63 64    chain.doFilter(wrapper, response);65 66   } else {//post67 68    req.setCharacterEncoding("UTF-8");69 70    chain.doFilter(request, response);71 72   }73  74  }75 76  /**77 78   * @see Filter#init(FilterConfig)79 80   */81 82  public void init(FilterConfig fConfig) throws ServletException {83 84  85  }86 87 }

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代码如下

 1 package com.example; 2  3 import java.io.IOException; 4  5 import javax.servlet.ServletException; 6  7 import javax.servlet.http.HttpServlet; 8  9 import javax.servlet.http.HttpServletRequest;10 11 import javax.servlet.http.HttpServletResponse;12 13 import com.example.EncodingHttpServletRequest;14 15 /**16 17  * Servlet implementation class ManageServlet18 19  */20 21 public class servlet extends HttpServlet {22 23  private static final long serialVersionUID = 1L;24 25       /**26 27      * @see HttpServlet#HttpServlet()28 29      */30 31     public servlet() {32 33         super();34 35     }36  37  /**38 39   * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)40 41   */42 43  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {44 45   String title = request.getParameter("title");46 47   EncodingHttpServletRequest requsete = new EncodingHttpServletRequest(request);48 49   String titlee = requsete.getParameter("title");50 51   //把客户端传递过来的参数进行重新编码使之能支持中文52 53   title = new String(title.getBytes("GB2312"),"UTF-8");//使用过滤器后就不需要每次都要进行此操作54 55   String timelength = request.getParameter("timelength");56 57   System.out.println("视频名称:"+titlee);58 59   System.out.println("播放时长:"+timelength);60 61  }62 63  /**64 65   * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)66 67   */68 69  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {70 71   String title = request.getParameter("title");72 73   //把客户端传递过来的参数进行重新编码使之能支持中文74 75   title = new String(title.getBytes("GB2312"),"UTF-8");//使用过滤器后就不需要每次都要进行此操作76 77   String timelength = request.getParameter("timelength");78 79   System.out.println("视频名称:"+title);80 81   System.out.println("播放时长:"+timelength);82 83  }84 }

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

 1 <servlet> 2  3    <servlet-name>servlet</servlet-name> 4  5    <servlet-class>com.example.servlet</servlet-class> 6  7  </servlet> 8  9  <servlet-mapping>10 11    <servlet-name>servlet</servlet-name>12 13    <url-pattern>/servlet</url-pattern>14 15   </servlet-mapping>

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

http://localhost:8080/http_service/servlet

 

客户端建立:

Http_androidActivity.java代码

 1 package com.example.newsmanage; 2 import android.app.Activity; 3 import android.os.Bundle; 4  5 public class Http_androidActivity extends Activity { 6     /** Called when the activity is first created. */ 7     @Override 8     public void onCreate(Bundle savedInstanceState) { 9 10         super.onCreate(savedInstanceState);11         setContentView(R.layout.main);12     }13 }

NewsManageActivity.java代码

 1 package com.example.newsmanage; 2  3 import com.example.service.NewsService; 4 import android.app.Activity; 5 import android.os.Bundle; 6 import android.view.View; 7 import android.widget.Button; 8 import android.widget.EditText; 9 import android.widget.Toast;10 11 public class NewsManageActivity extends Activity {12     /** Called when the activity is first created. */13  EditText titleText;14  EditText lengthText;15  Button button;16 17     @Override18     public void onCreate(Bundle savedInstanceState) {19 20         super.onCreate(savedInstanceState);21         setContentView(R.layout.main);     22 23         titleText = (EditText) this.findViewById(R.id.title);24         lengthText = (EditText) this.findViewById(R.id.timelength);25         button = (Button) this.findViewById(R.id.button);26     }27 28     public void save(View v) throws Exception{29 30      String title = titleText.getText().toString();31      String timelength = lengthText.getText().toString();32 33      boolean result = NewsService.save(title,timelength);34 35      if(result){36 37       Toast.makeText(getApplicationContext(), R.string.success, Toast.LENGTH_LONG).show();38 39      } else {40       Toast.makeText(getApplicationContext(), R.string.fail, Toast.LENGTH_LONG).show();41      }42     }43 }

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代码如下

 1 <?xml version="1.0" encoding="utf-8"?> 2  3 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 4  5     android:layout_width="fill_parent" 6  7     android:layout_height="fill_parent" 8  9     android:orientation="vertical" >10 11  12 13    <TextView14 15         android:layout_width="fill_parent"16 17         android:layout_height="wrap_content"18 19         android:text="@string/title" />20 21  22 23    <EditText24 25         android:id="@+id/title"26 27         android:layout_width="fill_parent"28 29         android:layout_height="wrap_content" >30 31  32 33         <requestFocus />34 35    </EditText>36 37  38 39    <TextView40 41         android:id="@+id/textView1"42 43         android:layout_width="fill_parent"44 45         android:layout_height="wrap_content"46 47         android:text="@string/timelength" />48 49  50 51    <EditText52 53         android:id="@+id/timelength"54 55         android:layout_width="fill_parent"56 57         android:layout_height="wrap_content" android:numeric="integer"/>58 59  60 61    <Button62 63         android:id="@+id/button"64 65         android:layout_width="wrap_content"66 67         android:layout_height="wrap_content"68 69         android:text="@string/button" android:onClick="save"/>70 71  72 73 </LinearLayout>

AndroidManifest.xml代码如下

 1 <?xml version="1.0" encoding="utf-8"?> 2  3 <manifest xmlns:android="http://schemas.android.com/apk/res/android" 4  5     package="com.example.newsmanage" 6  7     android:versionCode="1" 8  9     android:versionName="1.0" >10 11  12 13    <uses-sdk android:minSdkVersion="7" />14 15  16 17    <application18 19         android:icon="@drawable/ic_launcher"20 21         android:label="@string/app_name" >22 23         <activity24 25            android:name=".NewsManageActivity"26 27            android:label="@string/app_name" >28 29             <intent-filter>30 31                 <action android:name="android.intent.action.MAIN" />32 33  34 35                 <category android:name="android.intent.category.LAUNCHER" />36 37             </intent-filter>38 39         </activity>40 41    </application>42 43  <uses-permission android:name="android.permission.INTERNET"/>44 45    46 47 </manifest>

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

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

测试成功。

 

2、 socket形式

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

socket_service.java代码

  1 package example;  2   3    4   5    6   7 import java.io.BufferedReader;   8   9 import java.io.BufferedWriter;  10  11 import java.io.InputStreamReader;  12  13 import java.io.OutputStreamWriter;  14  15 import java.io.PrintWriter;   16  17 import java.net.ServerSocket;  18  19 import java.net.Socket;  20  21   22  23 public class socket_service implements Runnable  24  25 {   26  27     public void run()  28  29     {  30  31        try  32  33         {  34  35             //创建ServerSocket  36  37             ServerSocket serverSocket = new ServerSocket(54321);  38  39             while (true)  40  41             {  42  43                //接受客户端请求  44  45                Socket client = serverSocket.accept();  46  47                System.out.println("accept");  48  49                 try  50  51                 {  52  53                     //接收客户端消息  54  55                    BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream())); 56  57                    58  59                   System.out.print("\n"); 60  61                    String str = in.readLine();  62  63                   System.out.println("read:" + str);    64  65                     //向服务器发送消息  66  67                    PrintWriter out = new PrintWriter( new BufferedWriter( new OutputStreamWriter(client.getOutputStream())),true);        68  69                     out.println("server ");   70  71                    //关闭流  72  73                    out.close();   74  75                    in.close();  76  77                }  78  79                 catch (Exception e)  80  81                 {  82  83                    System.out.println(e.getMessage());  84  85                     e.printStackTrace();  86  87                 }  88  89                 finally  90  91                 {  92  93                     //关闭  94  95                    client.close();  96  97                    System.out.println("close");  98  99                } 100 101             } 102 103        }  104 105        catch (Exception e) 106 107         { 108 109            System.out.println(e.getMessage()); 110 111        } 112 113     } 114 115     //main函数,开启服务器 116 117    public static void main(String args[]) 118 119    { 120 121         Thread desktopServerThread = new Thread(new socket_service()); 122 123        desktopServerThread.start(); 124 125   } 126 127 }

客户端建立

Activity01.java代码

  1 package com.example.socket;  2   3    4   5 import java.io.BufferedReader;   6   7 import java.io.BufferedWriter;   8   9 import java.io.InputStreamReader;  10  11 import java.io.OutputStreamWriter;  12  13 import java.io.PrintWriter;  14  15 import java.net.Socket;  16  17   18  19 import android.app.Activity;  20  21 import android.os.Bundle;  22  23 import android.util.Log;  24  25 import android.view.View;  26  27 import android.view.View.OnClickListener;  28  29 import android.widget.Button;  30  31 import android.widget.EditText;  32  33 import android.widget.TextView;  34  35   36  37 public class Activity01 extends Activity  38  39 {  40  41     private final String        DEBUG_TAG   = "Activity01";  42  43      44  45    private TextView    mTextView = null;  46  47     private EditText    mEditText = null;  48  49     private Button      mButton = null;  50  51     /** Called when the activity is first created. */  52  53    @Override  54  55    public void onCreate(Bundle savedInstanceState)  56  57     {  58  59        super.onCreate(savedInstanceState);  60  61       setContentView(R.layout.main);  62  63          64  65        mButton = (Button)findViewById(R.id.Button01);  66  67        mTextView = (TextView)findViewById(R.id.TextView01);  68  69         mEditText = (EditText)findViewById(R.id.EditText01);  70  71           72  73         //登陆  74  75         mButton.setOnClickListener(new OnClickListener()  76  77        {  78  79            public void onClick(View v)  80  81            {  82  83                Socket socket = null;  84  85                String message = mEditText.getText().toString() + "/r/n";   86  87                 try   88  89                {     90  91                    //创建Socket  92  93                   socket = new Socket("192.168.1.2",54321);   94  95                     //socket = new Socket("10.14.114.127",54321); //IP:10.14.114.127,端口54321  96  97                    //向服务器发送消息  98  99                    PrintWriter out = new PrintWriter( new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())),true);       100 101                   out.println(message+"wmy");  102 103                      104 105                    //接收来自服务器的消息 106 107                    BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));  108 109                    String msg = br.readLine();  110 111                      112 113                    if ( msg != null ) 114 115                    { 116 117                       mTextView.setText(msg); 118 119                  } 120 121                     else 122 123                   { 124 125                         mTextView.setText("数据错误!"); 126 127                     } 128 129                     //关闭流 130 131                    out.close(); 132 133                     br.close(); 134 135                     //关闭Socket 136 137                     socket.close();  138 139                } 140 141               catch (Exception e)  142 143                { 144 145                    // TODO: handle exception 146 147                   Log.e(DEBUG_TAG, e.toString()); 148 149                } 150 151             } 152 153        }); 154 155    } 156 157 } 

Socket_androidActivity.java代码

 1 package com.example.socket; 2  3   4  5 import android.app.Activity; 6  7 import android.os.Bundle; 8  9  10 11 public class Socket_androidActivity extends Activity {12 13     /** Called when the activity is first created. */14 15     @Override16 17     public void onCreate(Bundle savedInstanceState) {18 19         super.onCreate(savedInstanceState);20 21         setContentView(R.layout.main);22 23     }24 25 }

Main.xml代码

 1 <?xml version="1.0" encoding="utf-8"?>  2  3 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  4  5     android:orientation="vertical"  6  7     android:layout_width="fill_parent"  8  9     android:layout_height="fill_parent" 10 11     > 12 13    <TextView   14 15     android:id="@+id/TextView01"  16 17     android:layout_width="fill_parent"  18 19     android:layout_height="wrap_content"  20 21     android:text="杩欓噷鏄剧ず鎺ユ敹鍒版湇鍔″櫒鍙戞潵鐨勪俊鎭? 22 23     /> 24 25     <EditText  26 27     android:id="@+id/EditText01"  28 29     android:text="杈撳叆瑕佸彂閫佺殑鍐呭"  30 31     android:layout_width="fill_parent"  32 33     android:layout_height="wrap_content"> 34 35    </EditText> 36 37    <Button  38 39     android:id="@+id/Button01" 40 41     android:layout_width="fill_parent" 42 43     android:layout_height="wrap_content" 44 45     android:text="鍙戦?" 46 47     />   48 49 </LinearLayout> 

AndroidManifest.xml

 1 <?xml version="1.0" encoding="utf-8"?> 2  3 <manifest xmlns:android="http://schemas.android.com/apk/res/android" 4  5     package="com.example.socket" 6  7     android:versionCode="1" 8  9     android:versionName="1.0" >10 11  12 13    <uses-sdk android:minSdkVersion="7" />14 15  16 17    <application18 19         android:icon="@drawable/ic_launcher"20 21         android:label="@string/app_name" >22 23         <activity24 25            android:name=".Activity01"26 27            android:label="@string/app_name" >28 29             <intent-filter>30 31                 <action android:name="android.intent.action.MAIN" />32 33  34 35                 <category android:name="android.intent.category.LAUNCHER" />36 37             </intent-filter>38 39         </activity>40 41    </application>42 43  <uses-permission android:name="android.permission.INTERNET"></uses-permission>44 45 </manifest>

开发好了就行测试吧

前后对比一下

服务器端:

参考原文:http://m.oschina.net/blog/75407

 

【Android笔记】Android与服务器通信 http和socket两种形式