android学习——网络访问HttpURLConnection

我们知道大多数的 Android 应用程序都是通过和服务器进行交互来获取数据的。如果使用 HTTP 协议来发送和接收网络数据,就免不了使用 HttpURLConnection 和 HttpClient,而 Android 中主要提供了上述两种方式来进行 HTTP 操作。并且这两种方式都支持 HTTPS 协议、以流的形式进行上传和下载、配置超时时间、IPv6、以及连接池等功能。

但是 Googl e发布 6.0 版本的时候声明原生剔除 HttpClient,详情可以看http://blog.csdn.net/guolin_blog/article/details/12452307。

接着我们来看一下如何使用 HttpURLConnection 的GET和POST来处理简单的用户登录请求。



<span style="white-space:pre">	</span>// 点击按钮 进行get方式提交数据
<span style="white-space:pre">	</span>public void click1(View v) {
<span style="white-space:pre">		</span>
<span style="white-space:pre">		</span>new Thread(){public void run() {
<span style="white-space:pre">			</span>


<span style="white-space:pre">			</span>try {
<span style="white-space:pre">			</span>//获取用户名和密码 
<span style="white-space:pre">			</span>String name = et_username.getText().toString().trim();
<span style="white-space:pre">			</span>String pwd = et_password.getText().toString().trim();
<span style="white-space:pre">			</span>//定义get方式要提交的路径    小细节 如果提交中文要对name 和 pwd 进行一个urlencode 编码 
<span style="white-space:pre">			</span>String path = "http://192.168.11.73:8080/login/LoginServlet?username="+URLEncoder.encode(name, "utf-8")+"&password="+URLEncoder.encode(pwd, "utf-8")+"";
<span style="white-space:pre">		</span>
<span style="white-space:pre">				</span>//(1) 创建一个url对象 参数就是网址 
<span style="white-space:pre">				</span>URL url = new URL(path);
<span style="white-space:pre">				</span>//(2)获取HttpURLConnection 链接对象
<span style="white-space:pre">				</span>HttpURLConnection conn = (HttpURLConnection) url.openConnection();
<span style="white-space:pre">				</span>//(3)设置参数  发送get请求
<span style="white-space:pre">				</span>conn.setRequestMethod("GET"); //默认请求 就是get  要大写
<span style="white-space:pre">				</span>//(4)设置链接网络的超时时间 
<span style="white-space:pre">				</span>conn.setConnectTimeout(5000);
<span style="white-space:pre">				</span>//(5)获取服务器返回的状态码 
<span style="white-space:pre">				</span>int code = conn.getResponseCode(); //200  代表获取服务器资源全部成功  206请求部分资源    
<span style="white-space:pre">				</span>if (code == 200) {
<span style="white-space:pre">					</span>//(6)获取服务器返回的数据  以流的形式返回   
<span style="white-space:pre">					</span>InputStream inputStream = conn.getInputStream();


<span style="white-space:pre">					</span>
<span style="white-space:pre">					</span>//(6.1)把inputstream 转换成 string 
<span style="white-space:pre">					</span>String content = readStream(inputStream);
<span style="white-space:pre">					</span>
<span style="white-space:pre">					</span>
<span style="white-space:pre">					</span>//(7)把服务器返回的数据展示到Toast上  不能在子线程展示toast
<span style="white-space:pre">					</span>showToast(content);
<span style="white-space:pre">					</span>
<span style="white-space:pre">					</span>
<span style="white-space:pre">				</span>}


<span style="white-space:pre">			</span>} catch (Exception e) {
<span style="white-space:pre">				</span>e.printStackTrace();
<span style="white-space:pre">			</span>}
<span style="white-space:pre">		</span>};}.start();
<span style="white-space:pre">		</span>
<span style="white-space:pre">		</span>
<span style="white-space:pre">		</span>
<span style="white-space:pre">	</span>}


<span style="white-space:pre">	</span>// [1]点击按钮 进行post方式提交数据
<span style="white-space:pre">	</span>public void click2(View v) {


<span style="white-space:pre">		</span>
<span style="white-space:pre">	</span>new Thread(){public void run() {
<span style="white-space:pre">			</span>try {
<span style="white-space:pre">			</span>//[2]获取用户名和密码 
<span style="white-space:pre">			</span>String name = et_username.getText().toString().trim();
<span style="white-space:pre">			</span>String pwd = et_password.getText().toString().trim();
<span style="white-space:pre">			</span>//[2.1]定义get方式要提交的路径 
<span style="white-space:pre">			</span>
<span style="white-space:pre">			</span>String data = "username="+URLEncoder.encode(name, "utf-8")+"&password="+URLEncoder.encode(pwd,"utf-8")+""; //请求体的内容
<span style="white-space:pre">			</span>
<span style="white-space:pre">			</span>// 一 ☆☆☆☆☆☆☆和get方式提交数据 区别 路径不同
<span style="white-space:pre">			</span>
<span style="white-space:pre">			</span>String path = "http://192.168.11.73:8080/login/LoginServlet";
<span style="white-space:pre">		</span>
<span style="white-space:pre">				</span>//(1) 创建一个url对象 参数就是网址 
<span style="white-space:pre">				</span>URL url = new URL(path);
<span style="white-space:pre">				</span>//(2)获取HttpURLConnection 链接对象
<span style="white-space:pre">				</span>HttpURLConnection conn = (HttpURLConnection) url.openConnection();
<span style="white-space:pre">				</span>//(3)设置参数  发送get请求
<span style="white-space:pre">				</span>
<span style="white-space:pre">		</span>    //二 ☆☆☆☆☆☆☆和get方式提交数据 区别  设置请求方式是post
<span style="white-space:pre">				</span>conn.setRequestMethod("POST"); //默认请求 就是get  要大写
<span style="white-space:pre">				</span>//(4)设置链接网络的超时时间 
<span style="white-space:pre">				</span>conn.setConnectTimeout(5000);
<span style="white-space:pre">				</span>
<span style="white-space:pre">				</span>
<span style="white-space:pre">			</span>//三 <span style="white-space:pre">	</span> ☆☆☆☆☆☆☆和get方式提交数据 区别 要多设置2个请求头信息 
<span style="white-space:pre">				</span>//设置头信息
<span style="white-space:pre">				</span>conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
<span style="white-space:pre">				</span>conn.setRequestProperty("Content-Length", data.length()+"");
<span style="white-space:pre">				</span>
<span style="white-space:pre">			</span>
<span style="white-space:pre">				</span>conn.setDoOutput(true);// 设置一个标记 允许输出 
<span style="white-space:pre">				</span>//四 ☆☆☆☆☆☆☆ 获得一个输出流,向服务器写数据,默认情况下,系统不允许向服务器输出内容 
<span style="white-space:pre">				</span>OutputStream out = conn.getOutputStream();
<span style="white-space:pre">				</span>out.write(data.getBytes());
<span style="white-space:pre">				</span>out.flush();  
<span style="white-space:pre">				</span>out.close(); 
<span style="white-space:pre">				
</span>
<span style="white-space:pre">				</span>
<span style="white-space:pre">				</span>//(5)获取服务器返回的状态码 
<span style="white-space:pre">				</span>int code = conn.getResponseCode(); //200  代表获取服务器资源全部成功  206请求部分资源    
<span style="white-space:pre">				</span>if (code == 200) {
<span style="white-space:pre">					</span>//(6)获取服务器返回的数据  以流的形式返回   
<span style="white-space:pre">					</span>InputStream inputStream = conn.getInputStream();
<span style="white-space:pre">					</span>
<span style="white-space:pre">					</span>//(6.1)把inputstream 转换成 string 
<span style="white-space:pre">					</span>String content = readStream(inputStream);
<span style="white-space:pre">					</span>
<span style="white-space:pre">					</span>
<span style="white-space:pre">					</span>//(7)把服务器返回的数据展示到Toast上  不能在子线程展示toast
<span style="white-space:pre">					</span>showToast(content);
<span style="white-space:pre">					</span>
<span style="white-space:pre">					</span>
<span style="white-space:pre">				</span>}


<span style="white-space:pre">			</span>} catch (Exception e) {
<span style="white-space:pre">				</span>e.printStackTrace();
<span style="white-space:pre">			</span>}
<span style="white-space:pre">		</span>};}.start();
<span style="white-space:pre">		</span>
<span style="white-space:pre">		</span>
<span style="white-space:pre">	</span>}
<span style="white-space:pre">	</span>
<span style="white-space:pre">	</span><pre name="code" class="java" style="color: rgb(51, 51, 51); font-size: 14px; line-height: 22.4px;">//封装把一个inputStream 转换成一个String的方法
 private static String readStream (InputStream is)
             throws IOException {
         ByteArrayOutputStream os = new ByteArrayOutputStream();
         // 模板代码 必须熟练
         byte[] buffer = new byte[1024];
         int len = -1;
         while ((len = is.read(buffer)) != -1) {
             os.write(buffer, 0, len);
         }
         is.close();
         String state = os.toString();// 把流中的数据转换成字符串,采用的编码是utf-8(模拟器默认编码)
         os.close();
         return state;
     }
//封装toast方法  该toast方法执行在主线程 
public void showToast(final String content){
runOnUiThread(new Runnable() {

@Override
public void run() {
//该方法一定是执行主线程 
Toast.makeText(getApplicationContext(), content, 1).show();


}
});

}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值