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 EncodingFilter 22 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 {//post 67 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 ManageServlet 18 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 @Override 18 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 <TextView 14 15 android:layout_width="fill_parent" 16 17 android:layout_height="wrap_content" 18 19 android:text="@string/title" /> 20 21 22 23 <EditText 24 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 <TextView 40 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 <EditText 52 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 <Button 62 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 <application 18 19 android:icon="@drawable/ic_launcher" 20 21 android:label="@string/app_name" > 22 23 <activity 24 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 @Override 16 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 <application 18 19 android:icon="@drawable/ic_launcher" 20 21 android:label="@string/app_name" > 22 23 <activity 24 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