1. 程式人生 > >Http網路請求

Http網路請求

get是從伺服器上獲取資料,post是向伺服器傳送資料
get傳送的資料量較小,不能大於2KB。post傳送的資料量較大,一般被預設為不受限制。但理論上,IIS4中最大量為80KB,IIS5中為100KB。
get安全性非常低,post安全性較高。但是執行效率卻比Post方法好。 
get方式的安全性較Post方式要差些,包含機密資訊的話,建議用Post資料提交方式;
在做資料查詢時,建議用Get方式;而在做資料新增、修改或刪除時,建議用Post方式;

HTTP GET請求
package com.zhidi.httpget;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {
	private EditText et_username;
	private EditText et_password;
	
	private Button bt_show;
	
	String result="";
	
	/**get請求URL地址*/
	private static final String URL="";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        init();
        
        bt_show.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				//android4.0後的新的特性,網路資料請求時不能放在主執行緒中。
				//7、使用執行緒執行訪問伺服器,獲取返回資訊後通知主執行緒更新UI或者提示資訊。
				final Handler handler = new Handler() {
                    @Override  
                    public void handleMessage(Message msg) {  
                        if (msg.what == 1) {
                        	//8、提示讀取結果
                	    	Toast.makeText(MainActivity.this, result, Toast.LENGTH_LONG).show();
                        }  
                    }  
                };
                // 啟動執行緒來執行任務  
                new Thread() {  
                    public void run() {
                    	//請求網路
                    	loginByGet(et_username.getText().toString(), et_password.getText().toString()); 
                        Message m = new Message();  
                        m.what = 1;  
                        // 傳送訊息到Handler  
                        handler.sendMessage(m);  
                    }  
                }.start();
                
			}
		});
        
    }
    
    private void init(){
    	et_username=(EditText)findViewById(R.id.et_username);
    	et_password=(EditText)findViewById(R.id.et_password);
    	bt_show=(Button)findViewById(R.id.bt_login);
    }
    
    /**
     * 請求後臺,判斷登入結果。
     * @param username
     * @param password
     */
    public void loginByGet(String username, String password) {  
        try {  
            //1、設定請求的地址。通過URLEncoder.encode(String s,"UTF-8")將字串轉換為UTF-8編碼
            String strUrl = URL  
                    +"?username=" + URLEncoder.encode(username, "UTF-8") 
                    + "&password=" + URLEncoder.encode(password, "UTF-8"); 
            //2、根據地址建立URL物件(網路訪問的url)  
            URL url = new URL(strUrl);  
            //3、url.openConnection()開啟網路連結  
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();  
            //4、獲取響應的輸入流物件
            InputStreamReader is = new InputStreamReader(conn.getInputStream());
            BufferedReader bufferedReader = new BufferedReader(is);
            StringBuffer strBuffer = new StringBuffer();
            String line = null;
            //5、讀取伺服器返回資訊
            while ((line = bufferedReader.readLine()) != null) {
                strBuffer.append(line);
            }
            result = strBuffer.toString();

	    	//6、關閉InputStream、關閉http連線
	    	is.close();
	    	conn.disconnect();
	    	
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
    } 
    
}

HTTP POST請求

package com.zhidi.httppost;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {
	private EditText et_username;
	private EditText et_password;
	
	private Button bt_show;
	
	String result="";
	
	/**post請求URL地址*/
	private static final String URL="";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        init();
        
        bt_show.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				//android4.0後的新的特性,網路資料請求時不能放在主執行緒中。
				//9、使用執行緒執行訪問伺服器,獲取返回資訊後通知主執行緒更新UI或者提示資訊。
				final Handler handler = new Handler() {
                    @Override  
                    public void handleMessage(Message msg) {  
                        if (msg.what == 1) {
                        	//8、提示讀取結果
                	    	Toast.makeText(MainActivity.this, result, Toast.LENGTH_LONG).show();
                        }  
                    }  
                };
                // 啟動執行緒來執行任務  
                new Thread() {  
                    public void run() {
                    	//請求網路
                    	loginByPost(et_username.getText().toString(), et_password.getText().toString()); 
                        Message m = new Message();  
                        m.what = 1;  
                        // 傳送訊息到Handler  
                        handler.sendMessage(m);  
                    }  
                }.start();
                
			}
		});
        
    }
    
    private void init(){
    	et_username=(EditText)findViewById(R.id.et_username);
    	et_password=(EditText)findViewById(R.id.et_password);
    	bt_show=(Button)findViewById(R.id.bt_login);
    }
    
    /**
     * 請求後臺,判斷登入結果。
     * @param username
     * @param password
     */
    public void loginByPost(String username, String password) {  
        try { 
            //1、根據地址建立URL物件(網路訪問的url)  
            URL url = new URL(URL);  
            //2、url.openConnection()開啟網路連結  
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();  
            //3、設定請求的方式  
            conn.setRequestMethod("POST"); 
            conn.setDoInput(true);//傳送POST請求必須設定允許輸出
            conn.setDoOutput(true);//傳送POST請求必須設定允許輸入
            //4、設定請求的頭
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            conn.setRequestProperty("Charset", "utf-8");
            String data = "username=" + URLEncoder.encode(username, "UTF-8")  
                    + "&password=" + URLEncoder.encode(password, "UTF-8");//傳遞的資料
            conn.setRequestProperty("Content-Length",String.valueOf(data.getBytes().length)); 
            //5、獲取輸出流 
            OutputStream os = conn.getOutputStream();  
            os.write(data.getBytes());  
            os.flush(); 
            
            
            //6、獲取響應的輸入流物件
            InputStreamReader is = new InputStreamReader(conn.getInputStream());
            BufferedReader bufferedReader = new BufferedReader(is);
            StringBuffer strBuffer = new StringBuffer();
            String line = null;
            //7、讀取伺服器返回資訊
            while ((line = bufferedReader.readLine()) != null) {
                strBuffer.append(line);
            }
            result = strBuffer.toString();

	    	//8、關閉InputStream、關閉http連線
	    	is.close();
	    	conn.disconnect();
	    	
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
    }
    
}

HttpClientGet請求
package com.zhidi.httpclientget;

import java.net.URLEncoder;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

/**
 * HttpClient get
 * @author Administrator
 */
public class MainActivity extends Activity {

	private EditText et_username;
	private EditText et_password;
	
	private Button bt_show;
	
	String result="";
	
	/**get請求URL地址*/
	private static final String URL="";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        init();
        
        bt_show.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				//android4.0後的新的特性,網路資料請求時不能放在主執行緒中。
				//7、使用執行緒執行訪問伺服器,獲取返回資訊後通知主執行緒更新UI或者提示資訊。
				final Handler handler = new Handler() {
                    @Override  
                    public void handleMessage(Message msg) {  
                        if (msg.what == 1) {
                        	//8、提示讀取結果
                	    	Toast.makeText(MainActivity.this, result, Toast.LENGTH_LONG).show();
                        }  
                    }  
                };
                // 啟動執行緒來執行任務  
                new Thread() {  
                    public void run() {
                    	//請求網路
                    	loginByHttpClientGet(et_username.getText().toString(), et_password.getText().toString()); 
                        Message m = new Message();  
                        m.what = 1;  
                        // 傳送訊息到Handler  
                        handler.sendMessage(m);  
                    }  
                }.start();
                
			}
		});
        
    }
    
    private void init(){
    	et_username=(EditText)findViewById(R.id.et_username);
    	et_password=(EditText)findViewById(R.id.et_password);
    	bt_show=(Button)findViewById(R.id.bt_login);
    }
    
    /**
     * 請求後臺,判斷登入結果。
     * @param username
     * @param password
     */
    public void loginByHttpClientGet(String username,String password) {
    	//1、建立 HttpClient的例項 
        HttpClient httpClient = new DefaultHttpClient();
        try { 
            //2、建立某種連線方法的例項,在這裡是HttpGet。 
        	String strUrl = URL  
                    +"?username=" + URLEncoder.encode(username, "UTF-8") 
                    + "&password=" + URLEncoder.encode(password, "UTF-8"); 
            HttpGet httpGet = new HttpGet(strUrl);
            
            //3、獲取HttpResponse例項
            HttpResponse httpResp = httpClient.execute(httpGet);
            //4、判斷是否能夠請求成功
            if(httpResp.getStatusLine().getStatusCode()==200){          
            	//5、獲取返回的資料
            	result = EntityUtils.toString(httpResp.getEntity(),"UTF-8");
            } else {
            	Log.i("HttpClientGet", "HttpGet方式請求失敗");
            }
        } catch (Exception e) {  
            e.printStackTrace(); 
        }finally {
            // 6、釋放連線。無論執行方法是否成功,都必須釋放連線  
        	httpClient.getConnectionManager().shutdown();//釋放連結  
        }       
    }
   
}


HttpClientPost請求

package com.zhidi.httpclientpost;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
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;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
/**
 * HttpClient post
 * @author Administrator
 */
public class MainActivity extends Activity {
	private EditText et_username;
	private EditText et_password;
	
	private Button bt_show;
	
	String result="";
	
	/**post請求URL地址*/
	private static final String URL="";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        init();
        
        bt_show.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				//android4.0後的新的特性,網路資料請求時不能放在主執行緒中。
				//8、使用執行緒執行訪問伺服器,獲取返回資訊後通知主執行緒更新UI或者提示資訊。
				final Handler handler = new Handler() {
                    @Override
                    public void handleMessage(Message msg) {  
                        if (msg.what == 1) {
                        	//9、提示讀取結果
                	    	Toast.makeText(MainActivity.this, result, Toast.LENGTH_LONG).show();
                        }  
                    }  
                };
                // 啟動執行緒來執行任務  
                new Thread() {  
                    public void run() {
                    	//請求網路
                    	loginByHttpClientPost(et_username.getText().toString(), et_password.getText().toString()); 
                        Message m = new Message();  
                        m.what = 1;  
                        // 傳送訊息到Handler  
                        handler.sendMessage(m);  
                    }  
                }.start();
                
			}
		});
        
    }
    
    private void init(){
    	et_username=(EditText)findViewById(R.id.et_username);
    	et_password=(EditText)findViewById(R.id.et_password);
    	bt_show=(Button)findViewById(R.id.bt_login);
    }
    
    /**
     * 請求後臺,判斷登入結果。
     * @param username
     * @param password
     */
    public void loginByHttpClientPost(String username,String password) {
    	//1.建立 HttpClient的例項  
        HttpClient httpClient = new DefaultHttpClient();
        try {
	        //2、建立某種連線方法的例項,在這裡是HttpPost。
	        HttpPost httpPost = new HttpPost(URL);  
            //3、封裝傳遞引數的集合  
            List<NameValuePair> parameters = new ArrayList<NameValuePair>();  
            parameters.add(new BasicNameValuePair("username", username));//往這個集合中新增你要傳遞的引數  
            parameters.add(new BasicNameValuePair("password", password));
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters, "UTF-8");//建立傳遞引數封裝 實體物件,設定傳遞引數的編碼  
            httpPost.setEntity(entity);//把實體物件存入到httpPost物件中 
            //4、呼叫HttpClient例項的execute方法來執行建立好的method例項
            HttpResponse httpResp = httpClient.execute(httpPost);
            //5、判斷是否能夠請求成功
            if(httpResp.getStatusLine().getStatusCode()==200){
            	//6、獲取返回的資料
            	result = EntityUtils.toString(httpResp.getEntity(),"UTF-8");
            } else {
            	Log.i("HttpClientPost", "HttpPost方式請求失敗");
            }
        }catch (Exception e) {  
            e.printStackTrace(); 
        }finally {
            // 7、釋放連線。無論執行方法是否成功,都必須釋放連線  
            httpClient.getConnectionManager().shutdown();//釋放連結  
        }
    	
    }
    
}