初学使用HttpURLConnection访问网络之发送GET请求

初学使用HttpURLConnection访问网络之发送GET请求

今天心血来潮,学习一下安卓客户端如何连接网络的,废话不多说,直接上菜。
一、首先是新建一个安卓项目,并且修改默认布局,我写的布局管理非常简单,如下所示
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <TableLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        >
        <TableRow >
            <TextView 
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="用户名:"
                />
            <EditText 
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:id="@+id/e_username"
                />
        </TableRow>
        <TableRow >
            <TextView 
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="密码:"
                />
            <EditText 
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:id="@+id/e_password"
                />
        </TableRow>
        <TableRow >
            <Button 
                android:id="@+id/b_submit"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="提交"
                />
        </TableRow>
    </TableLayout>
    <ScrollView
        android:id="@+id/scroll1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        >
        <TextView 
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/display"
                />
    </ScrollView>
</LinearLayout>

注意,别忘了在AndroidManifest.xml配置文件中增加网络权限<uses-permission android:name="android.permission.INTERNET"/>

二、
1、在MainActivity类中添加属性,并且在onCreate方法中获取相关的组件(此处就省略了哦)。
2、定义一个send()方法,用于传入数据到web端,并且获取web端返回的内容,注意,如果自己测试的话,如何连接让自己的电脑的web项目在外网能够访问呢,后面会说到。
注意:有的书上说那个连接的地址带多个参数的话中间用“,”隔开,我试了很多次都没有成功,最终还是用jsp页面中最常用的“&”成功了。
private void send(){
		//即将连接的url地址
		String http_url = "http://116.255.158.245:10002/Test/httpPost.jsp?username="
				+base64(e_username.getText().toString().trim())
				+"&password="+base64(e_password.getText().toString().trim());
		try {
			URL url = new URL(http_url);//创建URL对象
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();//创建一个HTTP连接
			if(connection != null){
				connection.setConnectTimeout(3000);//a设置连接超时时间,此处可不要
				connection.setRequestMethod("GET");//设置发送方式,默认就是GET方式
				InputStreamReader in = new InputStreamReader(connection.getInputStream());//获得读取的内容
				BufferedReader reader = new BufferedReader(in);
				String inputLine = null;
				//循环读取输入流中的内容
				while((inputLine = reader.readLine()) != null){
					result += inputLine + "\n";
				}
				in.close();//关闭输入流
				connection.disconnect();//关闭连接
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
上面用到base64(String content)方法是对内部的字符串进行base64编码,如下
private String base64(String content){
		try {
			//进行Base64编码
			content = Base64.encodeToString(content.getBytes("utf-8"), Base64.DEFAULT);
			//对字符串进行URL编码,不可以少哦
			content = URLEncoder.encode(content);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return content;
	}
3、上面的做好之后,就可以再oncreate方法中写真正的安卓代码了(虽然就几行),如下所示
protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		button = (Button)findViewById(R.id.b_submit);
		e_username = (EditText)findViewById(R.id.e_username);
		e_password = (EditText)findViewById(R.id.e_password);
		display = (TextView)findViewById(R.id.display);
		button.setOnClickListener(new View.OnClickListener() {
			public void onClick(View arg0) {
				if("".equals(e_username.getText().toString())){
					Toast.makeText(MainActivity.this, "用户名不能为空!", Toast.LENGTH_LONG).show();
					return;
				}
				
				if("".equals(e_password.getText().toString())){
					Toast.makeText(MainActivity.this, "密码不能为空!", Toast.LENGTH_LONG).show();
					return;
				}
				new Thread(new Runnable(){
					public void run() {
						send();//发送内容到服务器,并且获取jsp页面的内容
						Message m = handler.obtainMessage();//读取一个Message
						handler.sendMessage(m);//发送消息
					}
					
				}).start();//开启线程,注意此处比较容易忘记
				
			}
		});
		handler = new Handler(){
			@Override
			public void handleMessage(Message msg) {
				if(result != null){
					display.setText(result);
					e_username.setText("");
					e_password.setText("");
				}
				super.handleMessage(msg);
			}
		};
	}
至此,安卓端的代码基本上就完成了。下面是web端的代码了,更少更简单


三、重新打开一个Eclipse,并且新建一个web 项目,我的项目名称是Test,在项目中新建一个httpPost.jsp页面,页面中就是获取数据并且显示,这个页面的名称就是url里面那个哦,具体代码如下:
<%@page import="sun.misc.BASE64Decoder"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
	String username = request.getParameter("username");
	String password = request.getParameter("password");
	
	BASE64Decoder decoder = new BASE64Decoder();
	if(username !=null){
		username = username.replaceAll("%2B", "+");
		username = new String(decoder.decodeBuffer(username),"utf-8");
		request.setAttribute("username", username);
	}
	if(password !=null){
		password = password.replaceAll("%2B", "+");
		password = new String(decoder.decodeBuffer(password),"utf-8");
		request.setAttribute("password", password);
	}
%>
用户名如下:
${username}

密码如下:
${password}
到这为止,测试已经基本上完成了,但是总觉得在本地用虚拟机测试的话好像没什么意思,如何让手机客户端和web项目部在一个内网里面测试呢?请看继续往下看。

正常的情况下,你写的web项目在同一个局域网里面的人通过浏览器连接你的ip地址是可以访问的,但是如果要外网的人也要访问的话就需要配置映射了,但是我这里就悲哀了,不知道路由器的登录用户名和密码,于是我找了个软件,个人觉得这个软件还行,起码可以将你的web 项目映射出去,不足的地方就是有广告和只能映射一个端口出去,如果想映射多个或者没有广告的话还需要付费。
软件下载地址 点击打开链接
软件使用方法非常简单,打开软件配置右击列表显示的信息,在新窗口中配置你的tomcat端口即可,注意:在非付费的情况下设置的端口最好不要和别人的冲突,不然会经常端口。设置好以后看状态,开启的情况下即可。为了确保你的端口已经映射出去,最好用测试一下。
以上都成功的情况下,允许tomcat服务器发布网页,然后允许安卓项目即可。
谢谢




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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值