Android基础笔记——HttpURLConnection实现用户登录

来源:互联网 发布:淘宝有团购吗 编辑:程序博客网 时间:2024/06/18 08:55

Android可以用HttpURLConnection或HttpClient接口来开发网络程序。

网络通信使用最多的是Get和Post。Get和Post的不同之处在于Get的参数放在URL字符中,而Post的参数放在http请求数据中,通过输出流的方式发送给服务器。

主要步骤为:

1、创建一个URL对象:

URL url = new URL("http://XXXXXXX");</span>

用户登录存在用户名和密码的参数,如果是GET方式,那么需要将参数加载URL后面,如果是POST的方式,需要将参数作为输出流的方式发送给服务器:

GET方式:

String data = "username=" + userName + "&password=" + password;URL url = new URL("http://XXXX?" + data);
POST方式:
String data = "username=" + username + "&password=" + password;// 获得一个输出流,向服务器写数据,默认情况下,不允许程序向服务器输出数据OutputStream os = conn.getOutputStream();os.write(data.getBytes());os.flush();os.close();

在实际应用中需要考虑中文的编码问题,

2、通过url.openConnection()获得HttpURLConnection(HttpURLConnection继承自URLConnection,都是抽象类,无法直接实例化对象。):

HttpURLConnection conn = (HttpURLConnection) url.openConnection();
3、设置HttpURLConnection的各项参数:

// get或者post必须得全大写conn.setRequestMethod("GET");// 连接的超时时间conn.setConnectTimeout(10000);// 读数据的超时时间conn.setReadTimeout(5000);

POST方式需要向服务器发送输出流,所以要添加一个参数设置:

// 只有设置为TRUE,才能运行程序进行输出。conn.setDoOutput(true);

4、获得服务器端的返回码,判断是否连接成功:

int responseCode = conn.getResponseCode();if (responseCode == 200) {//连接成功} else {Log.i(tag, "访问失败: " + responseCode);}
5、如果连接成功的话,获得服务器端的输入流,并将输入流转化为字符串。从而判断是否登录成功

int responseCode = conn.getResponseCode();if (responseCode == 200) {InputStream is = conn.getInputStream();String state = getStringFromInputStream(is);return state;} else {Log.i(tag, "网络连接失败");}

在最后一定要调用 disconnect()方法将这个 HTTP连接关闭掉:

connection.disconnect();

为了用户友好,可将登录结果作为Toast弹出,提示用户。但是网络连接一般在子线程中操作,在子线程中弹出Toast可使用如下方法:

new Thread(new Runnable() {@Overridepublic void run() {// TODO Auto-generated method stubfinal String state = NetUtils.loginOfPost(username, password);runOnUiThread(new Runnable() {public void run() {Toast.makeText(MainActivity.this, state, 0).show();}});}}).start();



将输入流转化为字符串的代码如下:

public static String getStringFromInputStream(InputStream is) throws IOException {ByteArrayOutputStream baos = new ByteArrayOutputStream();byte[] buffer = new byte[1024];int len = -1;while ((len = is.read(buffer)) != -1) {baos.write(buffer, 0, len);}String result = baos.toString();is.close();baos.close();return result;}

GET和POST完整代码如下:

package com.example.loginget.utils;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URI;import java.net.URISyntaxException;import java.net.URL;import java.net.URLConnection;import java.net.URLEncoder;import android.net.Uri;import android.util.Log;public class NetUtils {private static String tag = "NetUtils";public static String loginOfPost(String username, String password) {HttpURLConnection conn = null;try {URL url = new URL("http://192.168.0.13:8080/ServerXXX/servlet/LoginServlet");conn = (HttpURLConnection) url.openConnection();conn.setRequestMethod("POST");conn.setConnectTimeout(5000);conn.setReadTimeout(5000);// 只有设置为TRUE,才能运行程序进行输入。conn.setDoOutput(true);String data = "username=" + username + "&password=" + password;// 获得一个输出流,向服务器写数据,默认情况下,不允许程序向服务器输出数据OutputStream os = conn.getOutputStream();os.write(data.getBytes());os.flush();os.close();int responseCode = conn.getResponseCode();if (responseCode == 200) {InputStream is = conn.getInputStream();String state = getStringFromInputStream(is);return state;} else {Log.i(tag, "网络连接失败");}} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();} finally {if (conn != null) {conn.disconnect();}}return null;}public static String loginOfGet(String userName, String password) {HttpURLConnection conn = null;try {// String data = "username=" + URLEncoder.encode(userName) +// "&password=" + URLEncoder.encode(password);String data = "username=" + userName + "&password=" + password;URL url = new URL("http://192.168.0.13:8080/ServerXXX/servlet/LoginServlet?" + data);conn = (HttpURLConnection) url.openConnection();// get或者post必须得全大写conn.setRequestMethod("GET");// 连接的超时时间conn.setConnectTimeout(10000);// 读数据的超时时间conn.setReadTimeout(5000);int responseCode = conn.getResponseCode();if (responseCode == 200) {//连接成功InputStream is = conn.getInputStream();String state = getStringFromInputStream(is);return state;} else {Log.i(tag, "访问失败: " + responseCode);}} catch (Exception e) {e.printStackTrace();} finally {if (conn != null) {conn.disconnect(); // 关闭连接}}return null;}public static String getStringFromInputStream(InputStream is) throws IOException {ByteArrayOutputStream baos = new ByteArrayOutputStream();byte[] buffer = new byte[1024];int len = -1;while ((len = is.read(buffer)) != -1) {baos.write(buffer, 0, len);}String result = baos.toString();is.close();baos.close();return result;}}

0 0
原创粉丝点击