Android -- 提交数据到服务器,Get Post方式, 异步Http框架提交

1. 发送请求到服务器有几种方式

(1)HttpURLConnection

(2)Httpclient 同步框架

(3)AsyncHttpClient 异步框架 (https://github.com/loopj/android-async-http 下载源码和lib包)

 

示例代码(3)示例 (最简便实用)

public void asyncGet(View v){		
		final String username = et_username.getText().toString().trim();
		final String password = et_password.getText().toString().trim();
		String uri = "http://192.168.1.100:8080/TestLogin/servlet/Login?"
				+ "username=" + URLEncoder.encode(username) 
				+ "&password=" + URLEncoder.encode(password);
		
		AsyncHttpClient client = new AsyncHttpClient();
        client.get(uri, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(String response) {
                Toast.makeText(MainActivity.this, response, Toast.LENGTH_SHORT).show();
            }

			@Override			
			public void onFailure(Throwable error, String content) {
				Toast.makeText(MainActivity.this, content, Toast.LENGTH_SHORT).show();
			}
                        
        });
	}
	
	public void asyncPost(View v){
		final String username = et_username.getText().toString().trim();
		final String password = et_password.getText().toString().trim();
		String uri = "http://192.168.1.100:8080/TestLogin/servlet/Login";
				
		AsyncHttpClient client = new AsyncHttpClient();
		RequestParams params = new RequestParams();
		params.put("username", username);
		params.put("password", password);
		
        client.post(uri, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(String response) {
                Toast.makeText(MainActivity.this, response, Toast.LENGTH_SHORT).show();
            }

			@Override			
			public void onFailure(Throwable error, String content) {
				Toast.makeText(MainActivity.this, content, Toast.LENGTH_SHORT).show();
			}
                        
        });
	}

 

示例代码 (1)(2)示例

public class MainActivity extends Activity {
	private EditText et_password;
	private EditText et_username;

	public void loginByGet(View paramView) {
		String str1 = this.et_password.getText().toString().trim();
		String str2 = this.et_username.getText().toString().trim();
		if ((TextUtils.isEmpty(str1)) || (TextUtils.isEmpty(str2))) {
			Toast.makeText(this, "用户名密码不能为空", 1).show();
			return;
		}
		try {
			String str3 = String
					.valueOf("http://192.168.1.100:8080/web/LoginServlet?");
			StringBuilder localStringBuilder1 = new StringBuilder(str3)
					.append("name=");
			String str4 = URLEncoder.encode(str2, "UTF-8");
			StringBuilder localStringBuilder2 = localStringBuilder1
					.append(str4).append("&password=");
			String str5 = URLEncoder.encode(str1, "UTF-8");
			String str6 = str5;
			HttpURLConnection localHttpURLConnection = (HttpURLConnection) new URL(
					str6).openConnection();
			localHttpURLConnection.setRequestMethod("GET");
			localHttpURLConnection.setConnectTimeout(5000);
			localHttpURLConnection
					.setRequestProperty(
							"User-Agent",
							"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET4.0C; .NET4.0E; .NET CLR 2.0.50727)");
			if (localHttpURLConnection.getResponseCode() == 200) {
				String str7 = StreamTools.readFromStream(localHttpURLConnection
						.getInputStream());
				Toast.makeText(this, str7, 1).show();
				return;
			}
		} catch (Exception localException) {
			localException.printStackTrace();
			Toast.makeText(this, "登陆失败", 1).show();
			return;
		}
		Toast.makeText(this, "登陆失败,http响应吗不正确.", 1).show();
	}

	public void loginByPost(View paramView) {
		String str1 = this.et_password.getText().toString().trim();
		String str2 = this.et_username.getText().toString().trim();
		if ((TextUtils.isEmpty(str1)) || (TextUtils.isEmpty(str2))) {
			Toast.makeText(this, "用户名密码不能为空", 1).show();
			return;
		}
		try {
			HttpURLConnection localHttpURLConnection = (HttpURLConnection) new URL(
					"http://192.168.1.100:8080/web/LoginServlet")
					.openConnection();
			localHttpURLConnection.setRequestMethod("POST");
			localHttpURLConnection.setRequestProperty("Content-Type",
					"application/x-www-form-urlencoded");
			StringBuilder localStringBuilder1 = new StringBuilder("name=");
			String str3 = URLEncoder.encode(str2, "UTF-8");
			StringBuilder localStringBuilder2 = localStringBuilder1
					.append(str3).append("&password=");
			String str4 = URLEncoder.encode(str1, "UTF-8");
			String str5 = str4;
			String str6 = String.valueOf(str5.length());
			String str7 = str6;
			localHttpURLConnection.setRequestProperty("Content-Length", str7);
			//允许对外写数据
			localHttpURLConnection.setDoOutput(true);
			OutputStream localOutputStream = localHttpURLConnection
					.getOutputStream();
			byte[] arrayOfByte = str5.getBytes();
			localOutputStream.write(arrayOfByte);
			localOutputStream.flush();
			if (localHttpURLConnection.getResponseCode() == 200) {
				String str8 = StreamTools.readFromStream(localHttpURLConnection
						.getInputStream());
				Toast.makeText(this, str8, 1).show();
				localOutputStream.close();
				return;
			}
		} catch (Exception localException) {
			Toast.makeText(this, "post登陆失败", 1).show();
			return;
		}
		Toast.makeText(this, "post登陆失败,http响应吗不正确.", 1).show();
	}

	protected void onCreate(Bundle paramBundle) {
		super.onCreate(paramBundle);
		setContentView(R.layout.activity_main);
		EditText localEditText1 = (EditText) findViewById(R.id.et_username);
		this.et_username = localEditText1;
		EditText localEditText2 = (EditText) findViewById(R.id.et_password);
		this.et_password = localEditText2;
	}

	/**
	 * 采用httpclient的方式 用get提交数据到服务器
	 */

	public void loginByClientGet(View view) {
		String password = et_password.getText().toString().trim();
		String name = et_username.getText().toString().trim();
		if (TextUtils.isEmpty(name) || TextUtils.isEmpty(password)) {
			Toast.makeText(this, "用户名密码不能为空", 1).show();
			return;
		}
		// 1.打开浏览器
		HttpClient client = new DefaultHttpClient();
		// 2.输入浏览器的地址
		String uri = "http://192.168.1.100:8080/web/LoginServlet?" + "name="
				+ URLEncoder.encode(name) + "&password="
				+ URLEncoder.encode(password);
		HttpGet httpGet = new HttpGet(uri);
		// 3.敲回车.
		try {
			HttpResponse response = client.execute(httpGet);
			int code = response.getStatusLine().getStatusCode();
			if (code == 200) {
				InputStream is = response.getEntity().getContent();
				String result = StreamTools.readFromStream(is);
				Toast.makeText(this, result, 1).show();
			} else {
				Toast.makeText(this, "服务器异常", 1).show();
			}
		} catch (Exception e) {
			e.printStackTrace();
			Toast.makeText(this, "访问网络异常", 1).show();
		}

	}

	/**
	 * 采用httpclient post数据到服务器
	 */
	public void loginByClientPost(View view) {
		String password = et_password.getText().toString().trim();
		String name = et_username.getText().toString().trim();
		if (TextUtils.isEmpty(name) || TextUtils.isEmpty(password)) {
			Toast.makeText(this, "用户名密码不能为空", 1).show();
			return;
		}
		try {
			// 1.创建一个浏览器
			HttpClient client = new DefaultHttpClient();
			// 2.准备一个连接
			HttpPost post = new HttpPost(
					"http://192.168.1.100:8080/web/LoginServlet");
			// 要向服务器提交的数据实体
			List<NameValuePair> parameters = new ArrayList<NameValuePair>();
			parameters.add(new BasicNameValuePair("name", name));
			parameters.add(new BasicNameValuePair("password", password));
			UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters,
					"utf-8");
			post.setEntity(entity);
			// 3.敲回车
			HttpResponse response = client.execute(post);
			int code = response.getStatusLine().getStatusCode();
			if (code == 200) {
				InputStream is = response.getEntity().getContent();
				String result = StreamTools.readFromStream(is);
				Toast.makeText(this, result, 1).show();
			} else {
				Toast.makeText(this, "服务器异常", 1).show();
			}
		} catch (Exception e) {
			e.printStackTrace();
			Toast.makeText(this, "client post 失败", 1).show();
		}

	}
}


 

 

posted @ 2014-03-28 08:42  今晚打酱油_  阅读(371)  评论(0编辑  收藏  举报