Android之使用URLConnection进行网络编程

使用URLConnection进行网络编程~

       URL的openConnection()方法将返回一个URLConnection,该对象表示应用程序和URL之间的通信连接,程序可以通过URLConnection实例向该URL发送请求,读取URL引

用的资源。通常创建一个和URL的连接,并发送请求,读取此URL引用的资源。

需要如下步骤:

  a)通过调用URL对象openConnection()方法来

    创建URLConnection对象

  b)设置URLConnection的参数和普通请求属性

    conn.setRequestProperty("accept","*/*");

    conn.setRequestProperty("connection","Keep-Alive");

    conn.setRequestProperty("user-agent","Mozilla/4.0(compatible;MSIE 6.0;Windows NT 5.1;SV1)");

    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

    //发送POST请求必须设置如下两行

    conn.setDoInput(true):设置该URLConnectiondoInput请求头字段的值

    coon.setDoOutput(true):

  c)调用connect():打开到此URL引用的资源的通信链接(如果尚未建立这样的连接)。

    如果在已打开连接(此时 connected 字段的值为 true)的情况下调用 connect 方法,则忽略该调用.

    URLConnection 对象经历两个阶段:首先创建对象,然后建立连接。

        在创建对象之后,建立连接之前,可指定各种选项(例如doInput和UseCaches).连接后再进行设置就会发生错误。连接后才能进行的操作(例如getContentLength),如有必要,将隐式执行连接.

  d)如果只是发送GET方式请求,使用connect方法建立和远程资源之间的实际连接即可,在请求的地址中传入数据。

  如果需要发送Post方法请求。需要获取

  URLConnection实例对应的输出流来发送请求参数,

     PrintWriter out=new PrintWriter(conn.getOutputStream());

     //解决乱码问题

     String n=EncodingUtils.getString("张三".getBytes(),"UTF-8");

     out.write("name="+n+"&pwd="+pwd);

     out.flush();//刷新输出流的缓冲

  e)远程资源变为可用,程序可以访问远程资源的头字段或通过输入流读取远程资源的数据。

      getInputStream()获取输入流。

      从输入流读取response的数据。

 

注意:1)如果既要使用输入流读取URLConnection响应的内容,也要使用输出流发送请求参数,一定要先使用输出流,再使用输入流。

        2)借助于URLConnection类的帮助,应用程序可以非常方便地与指定站点交换信息,包括发送GET请求,POST请求,并获取网站的响应等。

代码编写步骤如下:

1.先写一个服务器-web工程

新建一个Servlet--LoginServlet,简单实现用户的登录~

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

   
    public LoginServlet() {
        // TODO Auto-generated constructor stub
    }

	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(request, response);
	}

	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String name=request.getParameter("name");
		String pwd=request.getParameter("pwd");
		System.out.println(name+"   "+pwd);
		OutputStream os=response.getOutputStream();
		if("xuxu".equals(name)&&"123".equals(pwd)){
			os.write(("成功").getBytes("UTF-8"));
		}else{
			os.write(("失败").getBytes("UTF-8"));
		}
		os.flush();
		os.close();
	}

}
2.新建一个android项目,在MainActivity中分别使用get方法和post方法实现用户的登录

public class MainActivity extends Activity {

	private EditText name,pwd;
	public void get(View view){
		new Thread(){
			public void run() {
				try {
					URL url=new URL("http://169.254.244.141:8090/ConnectionServlet/LoginServlet"+
				"?name="+name+"&pwd="+pwd);
					URLConnection conn=url.openConnection();
					conn.connect();//真正的建立网络连接
					BufferedReader reader=new BufferedReader(new InputStreamReader(conn.getInputStream()));
					String line=null;
					StringBuffer stringBuffer=new StringBuffer();//字符串,都可以存储和操作字符串,它是变量
					while ((line=reader.readLine())!=null) {
						stringBuffer.append(line);
					}
					System.out.println(stringBuffer.toString());
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			};
		}.start();
	}
	
	public void post(View view){
		new Thread(){
			public void run() {
				try {
					URL url=new URL("http://169.254.244.141:8090/ConnectionServlet/LoginServlet"
				);
					URLConnection conn=url.openConnection();
					//必须设置
					conn.setDoInput(true);
					conn.setDoOutput(true);
					
					conn.connect();//真正的建立网络连接
					
					PrintWriter printWriter=new PrintWriter(conn.getOutputStream());
					
					printWriter.write("name="+name+"&pwd="+pwd);
					printWriter.flush();
					printWriter.close();
					
					BufferedReader reader=new BufferedReader(new InputStreamReader(conn.getInputStream()));
					String line=null;
					StringBuffer stringBuffer=new StringBuffer();
					while ((line=reader.readLine())!=null) {
						stringBuffer.append(line);
					}
					System.out.println(stringBuffer.toString());
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			};
		}.start();
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		name=(EditText) findViewById(R.id.name);
		pwd=(EditText) findViewById(R.id.pwd);
	}

	
}
3.运行,把Tomcat打开~

效果图如下:




想要服务器和源码的:http://download.csdn.net/detail/qq_33642117/9583776


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值