Http学习小结

(新手常犯的一些小错误)

1.http协议下载和上传.http url connection  socket 等都是网络编程,所以一定要注意,测试的时候必须有网(局域网也行),因为理论上模拟器是和本地计算机分离的,所以不能用localhost之类的获取本机IP地址,再用模拟器访问本地服务器的时候,必须保证两者实在同一个局域网内。

2.网络访问需要用Intent权限;

3.Activity中的DialogToast不能放在子线程中,否则就会出现运行时异常

一个简单的App登录检测

MainActivity.java

package com.li.qqdemo_client;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import org.apache.http.HttpEntity;
import org.apache.http.util.EntityUtils;

import com.li.qqdemo_client.httputil.HttpUtil;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

public class MainActivity extends Activity {

	private EditText ed_userName;
	private EditText ed_pwd;
	private RadioGroup group;
	private RadioButton rb;
	private static final int SUCCESS = 1;
	private static final int FAILUER = 0;
	private Handler handler = new Handler() {
		private String result;
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			//重写handleMessage,获取链接成功之后的验证信息
			super.handleMessage(msg);
			switch (msg.what) {
			case SUCCESS:
				result = (String) msg.obj;//获取验证后的信息
				showDialog(result);//调用showDialog方法,消息提示
				break;
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		ed_userName = (EditText) findViewById(R.id.ed_userName);
		ed_pwd = (EditText) findViewById(R.id.ed_pwd);
		Button ok = (Button) findViewById(R.id.ok);
		group = (RadioGroup) findViewById(R.id.rg_method);
		
		ok.setOnClickListener(new OnClickListener() {
			private String name;
			private String password;

			@Override
			public void onClick(View view) {
				// TODO Auto-generated method stub
				//根据RadioGroup,单选按钮来选择调用GET或者POST方法向服务器发送请求
				rb = (RadioButton) findViewById(group.getCheckedRadioButtonId());
				name = ed_userName.getText().toString().trim();
				password = ed_pwd.getText().toString().trim();
				boolean check = checkLogin(name, password);//检测用户名和密码框是否为空
				if(!check){
					return;
				}
				new Thread(){
					@Override
					public void run() {
						// TODO Auto-generated method stub
						String content = getContent(name,password);//调用getContent方法得到服务器获取的信息
						if(content==null){
							return;
						}
						Message msg = new Message();		//将信息存放的Message中并发送给handler
						msg.what = SUCCESS;
						msg.obj = content;
						handler.sendMessage(msg);
					}
				}.start();
			}
		});
	}

	public String getContent(String name,String password) {
		String method = rb.getText().toString().trim();	//根据单选按钮得到请求方法
		String path = getPath(name, password);
		System.out.println(path);
		String result = null;
		HttpURLConnection conn = null;
		try {
			conn = (HttpURLConnection) new URL(path).openConnection();	//打开链接
			conn.setConnectTimeout(5000);
			conn.setRequestMethod(method);
			if(conn.getResponseCode()==200){
				InputStream is = conn.getInputStream();
				result = HttpUtil.wirte(is);	//将流信息保存到一个String变量里
			}
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			if(conn!=null){
				conn.disconnect();
			}
		}
		return result;
	}
	
	public boolean checkLogin(String name,String password){
		if(name.equals("")){
			Toast.makeText(getApplicationContext(), "用户名不能为空", 2000).show();
			return false;
		}else if(password.equals("")){
			Toast.makeText(getApplicationContext(), "密码不能为空", 2000).show();
			return false;
		}
		return true;
	}

	public String getPath(String name, String password) {
		String basePath = "http://172.21.115.4:9090/QQDemo_Server/";
		String request = "name=" + name + "&password=" + password;
		String path = basePath + "servlet/LoginServlet?" + request;
		return path;
	}
	
	public void showDialog(String msg){//可以重复利用该方法来提示
		AlertDialog.Builder buidler = new AlertDialog.Builder(this);
		buidler.setTitle("消息提醒").setMessage(msg).setPositiveButton("确定", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
			}
		});
		AlertDialog dialog = buidler.create();
		dialog.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;
	}
}

HttpUtil.java

package com.li.qqdemo_client.httputil;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;

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

public class HttpUtil {
	
	public static String wirte(InputStream is){
		try {
			BufferedReader br = new BufferedReader(new InputStreamReader(is));
			String len = null ;
			StringBuffer sb = new StringBuffer();
			while((len=br.readLine())!=null){
				sb.append(len);
			}
			is.close();
			return sb.toString();
		} catch (FileNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return null;
	}
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值