`
jgsj
  • 浏览: 960733 次
文章分类
社区版块
存档分类
最新评论

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



分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics