1. 程式人生 > >Android GET,POST向伺服器端傳送資料(傳送)

Android GET,POST向伺服器端傳送資料(傳送)

//目錄結構


//strings.xml字元常量檔案

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <resources>  
  3.     <string name="title">通過Get和Post兩種方式分別提交資料到伺服器</string>  
  4.     <string name="app_name">GetAndPostRequest</string>  
  5.     <string name="book_name">書本名稱</string>  
  6.     <string name
    ="book_price">書本價格</string>  
  7.     <string name="success">提交成功</string>  
  8.     <string name="error">提交失敗</string>  
  9.     <string name="get_request">Get請求提交</string>  
  10.     <string name="post_request">Post請求提交</string>  
  11. </resources>  
//main.xml 佈局檔案
  1. <?
    xml
     version="1.0" encoding="utf-8"?>  
  2. <LinearLayout ="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="fill_parent"  
  4.     android:layout_height="fill_parent"  
  5.     android:orientation="vertical" >  
  6.     <TextView  
  7.         android:layout_width="fill_parent"  
  8.         android:layout_height
    ="wrap_content"  
  9.         android:text="@string/title" />  
  10.     <TextView   
  11.         android:layout_width="fill_parent"  
  12.         android:layout_height="wrap_content"  
  13.         android:text="@string/book_name"  
  14.         />  
  15.     <EditText   
  16.         android:id="@+id/book_name"  
  17.         android:layout_width="fill_parent"  
  18.         android:layout_height="wrap_content"  
  19.         />  
  20.     <TextView   
  21.         android:layout_width="fill_parent"  
  22.         android:layout_height="wrap_content"  
  23.         android:text="@string/book_price"  
  24.         />  
  25.     <EditText   
  26.         android:id="@+id/book_price"  
  27.         android:numeric="integer"  
  28.         android:layout_width="fill_parent"  
  29.         android:layout_height="wrap_content"  
  30.         />  
  31.     <LinearLayout   
  32.         android:orientation="horizontal"  
  33.         android:layout_width="fill_parent"  
  34.         android:layout_height="wrap_content"  
  35.         >  
  36.         <Button   
  37.             android:id="@+id/get_reqeust"  
  38.             android:layout_width="wrap_content"  
  39.             android:layout_height="wrap_content"  
  40.             android:text="@string/get_request"  
  41.             />  
  42.         <Button   
  43.             android:id="@+id/post_reqeust"  
  44.             android:layout_width="wrap_content"  
  45.             android:layout_height="wrap_content"  
  46.             android:text="@string/post_request"  
  47.             />  
  48.     </LinearLayout>  
  49. </LinearLayout>  
//RequestService.java 通過GET 和 Post請求的類
  1. package sn.len.request;  
  2. import java.io.OutputStream;  
  3. import java.net.HttpURLConnection;  
  4. import java.net.URL;  
  5. import java.net.URLEncoder;  
  6. import java.util.Map;  
  7. public class RequestService   
  8. {  
  9.     //get請求,有檔案長度大小限制   
  10.     public static boolean getRequest(String urlPath) throws Exception  
  11.     {  
  12.         URL url=new URL(urlPath);  
  13.         HttpURLConnection con=(HttpURLConnection)url.openConnection();  
  14.         con.setRequestMethod("GET");  
  15.         con.setReadTimeout(5*1000);  
  16.         if(con.getResponseCode()==200)  
  17.         {  
  18.             return true;  
  19.         }  
  20.         return false;  
  21.     }  
  22.     //post請求,無檔案長度大小限制   
  23.     public static boolean postRequest(String urlPath,Map<String,String> map) throws Exception  
  24.     {  
  25.         StringBuilder builder=new StringBuilder(); //拼接字元   
  26.         //拿出鍵值   
  27.         if(map!=null && !map.isEmpty())  
  28.         {  
  29.             for(Map.Entry<String, String> param:map.entrySet())  
  30.             {  
  31.                 builder.append(param.getKey()).append('=').append(URLEncoder.encode(param.getValue(), "utf-8")).append('&');  
  32.             }  
  33.             builder.deleteCharAt(builder.length()-1);  
  34.         }  
  35.         //下面的Content-Length: 是這個URL的二進位制資料長度   
  36.         byte b[]=builder.toString().getBytes();  
  37.         URL url=new URL(urlPath);  
  38.         HttpURLConnection con=(HttpURLConnection)url.openConnection();  
  39.         con.setRequestMethod("POST");  
  40.         con.setReadTimeout(5*1000);  
  41.         con.setDoOutput(true);//打開向外輸出   
  42.         con.setRequestProperty("Content-Type""application/x-www-form-urlencoded");//內容型別   
  43.         con.setRequestProperty("Content-Length",String.valueOf(b.length));//長度   
  44.         OutputStream outStream=con.getOutputStream();  
  45.         outStream.write(b);//寫入資料   
  46.         outStream.flush();//重新整理記憶體   
  47.         outStream.close();  
  48.         //狀態碼是不成功   
  49.         if(con.getResponseCode()==200)  
  50.         {  
  51.             return true;  
  52.         }  
  53.         return false;   
  54.     }  
  55. }  
//GetAndPostRequestActivity.java 主要的控制類
  1. package sn.len.getandpostreq;  
  2. import java.util.HashMap;  
  3. import java.util.Map;  
  4. import sn.len.request.RequestService;  
  5. import Android.app.Activity;  
  6. import android.os.Bundle;  
  7. import android.util.Log;  
  8. import android.view.View;  
  9. import android.view.View.OnClickListener;  
  10. import android.widget.EditText;  
  11. import android.widget.Toast;  
  12. public class GetAndPostRequestActivity extends Activity implements OnClickListener  
  13. {  
  14.     @Override  
  15.     public void onCreate(Bundle savedInstanceState)   
  16.     {  
  17.         super.onCreate(savedInstanceState);  
  18.         setContentView(R.layout.main);  
  19.         View get_button=findViewById(R.id.get_reqeust);  
  20.         View post_button=findViewById(R.id.post_reqeust);  
  21.         get_button.setOnClickListener(this);  
  22.         post_button.setOnClickListener(this);  
  23.     }  
  24.     @Override  
  25.     public void onClick(View v)   
  26.     {  
  27.         EditText book_name=(EditText)findViewById(R.id.book_name);  
  28.         EditText book_price=(EditText)findViewById(R.id.book_price);  
  29.         String bookname=book_name.getText().toString();  
  30.         String bookprice=book_price.getText().toString();  
  31.         switch(v.getId())  
  32.         {  
  33.             case R.id.get_reqeust: //Get請求   
  34.             {  
  35.                 //第一種可以用字串拼接   
  36.                 String urlPath="http://192.168.0.133/web/index.jsp"+"?type=save&book_name="+bookname+"&book_price="+bookprice+"";  
  37.                 String realPath=urlPath.replaceAll(" """);//把多餘的空格替換掉   
  38.                 try   
  39.                 {  
  40.                     if(RequestService.getRequest(realPath))  
  41.                     {  
  42.                         Toast.makeText(this, R.string.success, Toast.LENGTH_LONG).show();  
  43.                     }  
  44.                 }  
  45.                 catch (Exception e)   
  46.                 {  
  47.                     Toast.makeText(this, R.string.error, Toast.LENGTH_LONG).show();  
  48.                     e.printStackTrace();  
  49.                 }  
  50.             }break;  
  51.             case R.id.post_reqeust: //Post請求   
  52.             {  
  53.                 String urlPath="http://192.168.0.133/web/index.jsp";  
  54.                 Map<String,String> map=new HashMap<String,String>();//用集合來做,比字串拼接來得直觀   
  55.                 map.put("type""save");  
  56.                 map.put("book_name",bookname);  
  57.                 map.put("book_price",bookprice);  
  58.                 try   
  59.                 {  
  60.                     if(RequestService.postRequest(urlPath, map))  
  61.                     {  
  62.                         Toast.makeText(this, R.string.success, Toast.LENGTH_LONG).show();  
  63.                     }  
  64.                 }   
  65.                 catch (Exception e)   
  66.                 {  
  67.                     Toast.makeText(this, R.string.error, Toast.LENGTH_LONG).show();  
  68.                     Log.e("ERRORS", e.toString());  
  69.                     e.printStackTrace();  
  70.                 }  
  71.             }break;  
  72.             default:break;  
  73.         }  
  74.     }  
  75. }  
//伺服器端程式碼用JSP實現,就沒有寫Servlet了
  1. <%@page contentType="text/html" pageEncoding="GBK" language="java"%>  
  2. <%  
  3.     String type=request.getParameter("type");  
  4.     if(type!=null && !"".equals(type))  
  5.     {  
  6.         if(type.equals("save"))  
  7.         {  
  8.             String book_name=request.getParameter("book_name");  
  9.             String book_price=request.getParameter("book_price");  
  10.             if((book_name!=null && !"".equals(book_name)) && (book_price!=null && !"".equals(book_price)))  
  11.             {  
  12.                 System.out.println("書名"+book_name);  
  13.                 System.out.println("價格"+book_price);  
  14.             }  
  15.         }  
  16.     }  
  17. %>  
//效果


//Tomcat服務端響應效果,書名和價格都已經打出來了。