android中用GET和POST的方法向伺服器上傳資料

來源:互聯網
上載者:User

兩者的區別如下:

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();
  } 
 }
}

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.