Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> android中用GET和POST的方法向服務器上傳數據

android中用GET和POST的方法向服務器上傳數據

編輯:關於Android編程

兩者的區別如下:

GET上傳的數據一般是很小的並且安全性能不高的數據, 而POST上傳的數據適用於數據量大,數據類型復雜,數據安全性能要求高的地方

GET和POST的使用方法一般如下:

1.采用GET方式向服務器傳遞數據的步驟

1.利用Map集合對數據進行獲取並進行數據處理
if (params!=null&&!params.isEmpty()) {
 for (Map.Entry<String, String> entry:params.entrySet()) {
   
  sb.append(entry.getKey()).append("=");
  sb.append(URLEncoder.encode(entry.getValue(),encoding));
  sb.append("&");
   }
  sb.deleteCharAt(sb.length()-1);
  
  }
 
2.新建一個StringBuilder對象
  sb=new StringBuilder()
3.新建一個HttpURLConnection的URL對象,打開連接並傳遞服務器的path
connection=(HttpURLConnection) new URL(path).openConnection();
4.設置超時和連接的方式

 connection.setConnectTimeout(5000);
  connection.setRequestMethod("GET");


2.采用POST方式向服務器傳遞數據的步驟
 

1.利用Map集合對數據進行獲取並進行數據處理
if (params!=null&&!params.isEmpty()) {
 for (Map.Entry<String, String> entry:params.entrySet()) {
   
  sb.append(entry.getKey()).append("=");
  sb.append(URLEncoder.encode(entry.getValue(),encoding));
  sb.append("&");
   }
  sb.deleteCharAt(sb.length()-1);
  
  }
 
2.新建一個StringBuilder對象,得到POST傳給服務器的數據
  sb=new StringBuilder()
  byte[] data=sb.toString().getBytes();
3.新建一個HttpURLConnection的URL對象,打開連接並傳遞服務器的path
connection=(HttpURLConnection) new URL(path).openConnection();
4.設置超時和允許對外連接數據
connection.setDoOutput(true);
5.設置連接的setRequestProperty屬性

connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
  connection.setRequestProperty("Content-Length", data.length+"");
6.得到連接輸出流
outputStream =connection.getOutputStream();
7.把得到的數據寫入輸出流中並刷新
 outputStream.write(data);
 outputStream.flush();


 

3.具體實現的過程如下:
1.使用GET方法上傳數據
服務器中doGet方法中的代碼如下:

 

[java] view plaincopyprint?protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
         
        String name =request.getParameter("name"); 
        String age=request.getParameter("age"); 
        System.out.println("--------name:"+name); 
        System.out.println("--------age:"+age); 
         
    } 

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  
  String name =request.getParameter("name");
  String age=request.getParameter("age");
  System.out.println("--------name:"+name);
  System.out.println("--------age:"+age);
  
 }
在客戶端實現的代碼如下:

 

[java] view plaincopyprint?public class UserSerivce { 
 
    public static boolean save(String getname, String getage) throws Exception { 
 
        String path = "http://10.254.1.62/WebForGETMethod/ServletForGetMethod"; 
 
        Map<String, String> params = new HashMap<String, String>(); 
        params.put("name", getname); 
        params.put("age", getage); 
 
        return sendGETRequest(path, params, "UTF-8"); 
    } 
 
    private static boolean sendGETRequest(String path, 
            Map<String, String> params, String encoding) throws Exception { 
 
        StringBuilder sb = new StringBuilder(path); 
        if (params != null && !params.isEmpty()) { 
            sb.append("?"); 
            for (Map.Entry<String, String> entry : params.entrySet()) { 
 
                sb.append(entry.getKey()).append("="); 
                sb.append(URLEncoder.encode(entry.getValue(), encoding)); 
                sb.append("&"); 
            } 
            sb.deleteCharAt(sb.length() - 1); 
        } 
 
        HttpURLConnection connection = (HttpURLConnection) new URL( 
                sb.toString()).openConnection(); 
        connection.setConnectTimeout(5000); 
        connection.setRequestMethod("GET"); 
        if (connection.getResponseCode() == 200) { 
            return true; 
        } 
 
        return false; 
    } 
 

public class UserSerivce {

 public static boolean save(String getname, String getage) throws Exception {

  String path = "http://10.254.1.62/WebForGETMethod/ServletForGetMethod";

  Map<String, String> params = new HashMap<String, String>();
  params.put("name", getname);
  params.put("age", getage);

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

 private static boolean sendGETRequest(String path,
   Map<String, String> params, String encoding) throws Exception {

  StringBuilder sb = new StringBuilder(path);
  if (params != null && !params.isEmpty()) {
   sb.append("?");
   for (Map.Entry<String, String> entry : params.entrySet()) {

    sb.append(entry.getKey()).append("=");
    sb.append(URLEncoder.encode(entry.getValue(), encoding));
    sb.append("&");
   }
   sb.deleteCharAt(sb.length() - 1);
  }

  HttpURLConnection connection = (HttpURLConnection) new URL(
    sb.toString()).openConnection();
  connection.setConnectTimeout(5000);
  connection.setRequestMethod("GET");
  if (connection.getResponseCode() == 200) {
   return true;
  }

  return false;
 }

}
然後呢,就是實現在android客戶端的界面

 

[java] view plaincopyprint?public class GetDataToWebActivity extends Activity { 
private EditText name,age; 
    public void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.getdate); 
        name=(EditText) findViewById(R.id.name); 
        age=(EditText) findViewById(R.id.age); 
    } 
    public void save(View v) { 
        String getname=name.getText().toString(); 
        String getage=age.getText().toString(); 
         
        boolean result=false; 
        try { 
            result=UserSerivce.save(getname,getage); 
        } catch (Exception e) { 
            // TODO Auto-generated catch block  
            e.printStackTrace(); 
        } 
         
        if (result) { 
            Toast.makeText(this, "成功", 1).show(); 
             
        }else { 
            Toast.makeText(this, "失敗", 1).show(); 
        }    
    } 

public class GetDataToWebActivity extends Activity {
private EditText name,age;
 public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.getdate);
        name=(EditText) findViewById(R.id.name);
        age=(EditText) findViewById(R.id.age);
    }
 public void save(View v) {
  String getname=name.getText().toString();
  String getage=age.getText().toString();
  
  boolean result=false;
  try {
   result=UserSerivce.save(getname,getage);
  } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  
  if (result) {
   Toast.makeText(this, "成功", 1).show();
   
  }else {
   Toast.makeText(this, "失敗", 1).show();
  } 
 }
}

 

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved