android客戶端採用Post和Get方式向web服務器傳遞參數

android客戶端向web服務器傳遞參數主要用到了HttpURLConnection類,通過這個類,我們可以獲取到指定url的連接,在其中我們可以通過設定請求的方法是Post還是get,採用get方法相對容易,我們通過觀察瀏覽器中url可以發現,提交的參數和參數值都被附着到了URL的後面,因此在android客戶端中同樣是將參數和參數值直接附着在URL後面,而post方法向對方複雜,需要我們設置一些參數,並且以輸出流的形式向服務器端傳遞參數。

下面代碼實現了 將客戶端中用戶名和密碼傳遞到服務器端

public class MainActivity extends Activity {
	
	private Button loginButton;
	private EditText usernameText;
	private EditText passwordText;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
	
	loginButton = (Button) this.findViewById(R.id.login);
	usernameText = (EditText) this.findViewById(R.id.username);
	passwordText = (EditText) this.findViewById(R.id.password);
	
	loginButton.setOnClickListener(new OnClickListener(){

		@Override
		public void onClick(View v) {
			String username = usernameText.getText().toString();
			String password = passwordText.getText().toString();
			
		Map<String,String> map = new HashMap<String,String>();
		map.put("username", username);
		map.put("password",password);
		
			boolean result = RequestHandler.sendGetRequest(map);
			if(result){
				Toast.makeText(MainActivity.this, "登陸成功", Toast.LENGTH_SHORT).show();
			}else{
				Toast.makeText(MainActivity.this, "登陸失敗", Toast.LENGTH_SHORT).show();
			}
		}
	});
}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}
下面是RequestHandler類的代碼

public class RequestHandler {
	/*
	 * 通過get方法向服務器發送請求,主要是將請求的參數和參數值附着在請求地址後面。
	 */
	public static boolean sendGetRequest(Map<String,String> params){
		StringBuilder path = new StringBuilder("http://169.254.220.210:8080/android/LoginServlet?");
		for(Map.Entry<String, String> entry:params.entrySet()){
			
			path.append(entry.getKey());
			path.append("=");
			path.append(entry.getValue());
			path.append("&");	
		}
			path.deleteCharAt(path.length()- 1);  //去掉最後一個參數後面多餘的&
		
		try {
			URL url = new URL(path.toString());
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			connection.setConnectTimeout(500);
			connection.setRequestMethod("GET");
			if(connection.getResponseCode() == HttpURLConnection.HTTP_OK){
				return true;
			}
			
		} catch (Exception e) {
		
			e.printStackTrace();
			return false;
		}
		return false;
	}
	
	public static boolean sendPostRequest(Map<String,String> params){
		
		StringBuilder data = new StringBuilder();
		for(Map.Entry<String, String> entry : params.entrySet()){  //設置請求的參數
			data.append(entry.getKey());
			data.append("=");
			data.append(entry.getValue());
			data.append("&");
		}
		
		data.deleteCharAt(data.length() - 1);
		
		try {
			HttpURLConnection post = (HttpURLConnection) new URL("http://169.254.220.210:8080/android/LoginServlet").				openConnection();
			post.setConnectTimeout(500);
			post.setDoOutput(true);  //一定要將可以輸出參數設置爲true
			post.setRequestProperty("Content-Length",String.valueOf(data.length())); //必須設定請求的長度
			post.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");//必須設定請求的內容
			OutputStream out = post.getOutputStream();  
			out.write(data.toString().getBytes());  //通過輸出流將參數輸出
			
			//在輸出參數之後一定要獲取響應的某項內容,才能真正的發出post請求,在這裏獲取響應的狀態碼
			
			if(post.getResponseCode() == HttpURLConnection.HTTP_OK){   
				return true;
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return true;
		}
		
		return false;
	}
}



發佈了31 篇原創文章 · 獲贊 31 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章