Android开发-基础网络组件(1)使用HttpURLConnection登陆-AndroidStudio
2017-04-25 11:25
751 查看
转载请注明出处:http://blog.csdn.net/iwanghang/article/details/70685334
觉得博文有用,请点赞,请评论,请关注,谢谢!~
老规矩,先上GIF动态图,看个效果,如果符合你的项目或者确定你要了解的内容,再往下看吧:
![](https://oscdn.geek-share.com/Uploads/Images/Content/201911/11/f299a696317c92a548f1a36fd5e44b85)
接口使用php本地服务器,简单说就是使用phpStudy开启本地服务器,不会的同学请看我写的关于php的博文:
这个是最基础的方法来实现登陆,虽然方法比较low,但是了解原理来说,最好不过。只是,不建议在实际项目中使用,因为比较代码量比较大。
以下是php和Android的代码:
$action = isset($_POST['action']) ? $_POST['action'] : '';
$username = isset($_POST['username']) ? $_POST['username'] : '';
$password = isset($_POST['password']) ? $_POST['password'] : '';
if($action=='login') {
login($username, $password);
} else {
$result = array("login"=>"error");
$json = json_encode($result);
echo $json;
}
/*用户登录*/
function login($username, $password) {
$result = null;
if($username=="iwanghang" && $password=="123") {
$result = array("login"=>$username."---".$password."---success");
$json = json_encode($result);
}else{
$result = array("login"=>"账户名或密码操作");
$json = json_encode($result);
}
echo $json;
}
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.iwanghang.httpurlconnectiondemo.MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Hello World!"
android:id="@+id/textView_info" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:textSize="15sp"
android:text="账号"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textView2" />
<EditText
android:textSize="15sp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:hint="请输入用户名"
android:ems="10"
android:id="@+id/editText_userName" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:textSize="15sp"
android:text="密码"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textView3" />
<EditText
android:textSize="15sp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:hint="请输入密码"
android:ems="10"
android:id="@+id/editText_passWord"
android:layout_weight="1" />
</LinearLayout>
<Button
android:text="登陆"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="loginClick"
android:id="@+id/button_login" />
</LinearLayout>
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
public class MainActivity extends AppCompatActivity {
private TextView textView_info;
private EditText editText_userName;
private EditText editText_passWord;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView_info = (TextView) findViewById(R.id.textView_info);
editText_userName = (EditText) findViewById(R.id.editText_userName);
editText_passWord = (EditText) findViewById(R.id.editText_passWord);
}
public void loginClick(View view){
final String userName = editText_userName.getText().toString();
if (TextUtils.isEmpty(userName)){
textView_info.setText("用户名不能为空");
return;
}
final String passWord = editText_passWord.getText().toString();
if (TextUtils.isEmpty(passWord)){
textView_info.setText("密码不能为空");
return;
}
// 启动登陆工作线程
new Thread(new Runnable() {
@Override
public void run() {
// 接口地址
String path= "http://192.168.1.114/login.php";
// String path= "http://192.168.1.40/login.php";
try {
URL url = new URL(path);
// 打开http链接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setConnectTimeout(1000*30); // 连接超时时间
conn.setReadTimeout(1000*30); // 读取数据超时时间
conn.setUseCaches(false);
conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
// 对服务器端读取或者写入数据(使用输入输出流)
// 获取连接的输出流
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
// action=login 表示登陆 也可以等于别的 主要看你的php同事如何协商
// 一般来说 action=login 表示登陆 action=update 表示修改密码 不多赘述
// 接口php同事怎么写你就怎么传
dos.writeBytes("action="+ URLEncoder.encode("login","UTF8"));
dos.writeBytes("&username="+ URLEncoder.encode(userName,"UTF8"));
dos.writeBytes("&password="+ URLEncoder.encode(passWord,"UTF8"));
dos.flush();
dos.close();
// 从服务器获取相应数据
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String result = br.readLine();
System.out.println("result == " + result);
br.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
}
至此,可以AndroidStudio的控制台查看的服务器返回的结果,但是没有显示到UI上面,下一篇博文,我们把服务器的结果显示在UI上。
04-25 03:12:46.589 5373-7446/com.iwanghang.httpurlconnectiondemo I/System.out: result == {"login":"\u8d26\u6237\u540d\u6216\u5bc6\u7801\u64cd\u4f5c"}
----------
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.ref.WeakReference;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
public class MainActivity extends AppCompatActivity {
private TextView textView_info;
private EditText editText_userName;
private EditText editText_passWord;
private final MyHandler myHandler = new MyHandler(this);
private static final int LOAD_SUCESS = 0x1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView_info = (TextView) findViewById(R.id.textView_info);
editText_userName = (EditText) findViewById(R.id.editText_userName);
editText_passWord = (EditText) findViewById(R.id.editText_passWord);
}
public void loginClick(View view){
final String userName = editText_userName.getText().toString();
if (TextUtils.isEmpty(userName)){
textView_info.setText("用户名不能为空");
return;
}
final String passWord = editText_passWord.getText().toString();
if (TextUtils.isEmpty(passWord)){
textView_info.setText("密码不能为空");
return;
}
// 启动登陆工作线程
new Thread(new Runnable() {
@Override
public void run() {
// 接口地址
String path= "http://192.168.1.114/login.php";
// String path= "http://192.168.1.40/login.php";
try {
URL url = new URL(path);
// 打开http链接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setConnectTimeout(1000*30); // 连接超时时间
conn.setReadTimeout(1000*30); // 读取数据超时时间
conn.setUseCaches(false);
conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
// 对服务器端读取或者写入数据(使用输入输出流)
// 获取连接的输出流
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
// action=login 表示登陆 也可以等于别的 主要看你的php同事如何协商
// 一般来说 action=login 表示登陆 action=update 表示修改密码 不多赘述
// 接口php同事怎么写你就怎么传
dos.writeBytes("action="+ URLEncoder.encode("login","UTF8"));
dos.writeBytes("&username="+ URLEncoder.encode(userName,"UTF8"));
dos.writeBytes("&password="+ URLEncoder.encode(passWord,"UTF8"));
dos.flush();
dos.close();
// 从服务器获取相应数据
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String result = br.readLine();
System.out.println("result == " + result);
br.close();
conn.disconnect();
// 通过handler把result传出去
Message msg = myHandler.obtainMessage(LOAD_SUCESS,result);
myHandler.sendMessage(msg);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
private static class MyHandler extends Handler {
private final WeakReference<MainActivity> weakReference; // 软引用
public MyHandler(MainActivity mainActivity){
weakReference = new WeakReference<MainActivity>(mainActivity);
}
@Override
public void handleMessage(Message msg) {
MainActivity mainActivity = weakReference.get();
if (mainActivity!=null){
switch (msg.what){
case LOAD_SUCESS:
mainActivity.textView_info.setText((String)msg.obj); // 获取msg 设置UI显示
break;
}
}
}
}
}
转载请注明出处:http://blog.csdn.net/iwanghang/article/details/70685334
欢迎移动开发爱好者交流
沈阳或周边城市公司有意开发Android,请与我联系
联系方式
![](https://oscdn.geek-share.com/Uploads/Images/Content/201611/9b6ff7223ea78b1fb36a453adfcf46c5)
微信:iwanghang
QQ:413711276
邮箱:iwanghang@qq.com
觉得博文有用,请点赞,请评论,请关注,谢谢!~
觉得博文有用,请点赞,请评论,请关注,谢谢!~
老规矩,先上GIF动态图,看个效果,如果符合你的项目或者确定你要了解的内容,再往下看吧:
接口使用php本地服务器,简单说就是使用phpStudy开启本地服务器,不会的同学请看我写的关于php的博文:
这个是最基础的方法来实现登陆,虽然方法比较low,但是了解原理来说,最好不过。只是,不建议在实际项目中使用,因为比较代码量比较大。
以下是php和Android的代码:
php:
login.php:
<?php$action = isset($_POST['action']) ? $_POST['action'] : '';
$username = isset($_POST['username']) ? $_POST['username'] : '';
$password = isset($_POST['password']) ? $_POST['password'] : '';
if($action=='login') {
login($username, $password);
} else {
$result = array("login"=>"error");
$json = json_encode($result);
echo $json;
}
/*用户登录*/
function login($username, $password) {
$result = null;
if($username=="iwanghang" && $password=="123") {
$result = array("login"=>$username."---".$password."---success");
$json = json_encode($result);
}else{
$result = array("login"=>"账户名或密码操作");
$json = json_encode($result);
}
echo $json;
}
Android:
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.iwanghang.httpurlconnectiondemo.MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Hello World!"
android:id="@+id/textView_info" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:textSize="15sp"
android:text="账号"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textView2" />
<EditText
android:textSize="15sp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:hint="请输入用户名"
android:ems="10"
android:id="@+id/editText_userName" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:textSize="15sp"
android:text="密码"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textView3" />
<EditText
android:textSize="15sp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:hint="请输入密码"
android:ems="10"
android:id="@+id/editText_passWord"
android:layout_weight="1" />
</LinearLayout>
<Button
android:text="登陆"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="loginClick"
android:id="@+id/button_login" />
</LinearLayout>
MainActivity.java:(未使用handler设置textView_info)
package com.iwanghang.httpurlconnectiondemo;import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
public class MainActivity extends AppCompatActivity {
private TextView textView_info;
private EditText editText_userName;
private EditText editText_passWord;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView_info = (TextView) findViewById(R.id.textView_info);
editText_userName = (EditText) findViewById(R.id.editText_userName);
editText_passWord = (EditText) findViewById(R.id.editText_passWord);
}
public void loginClick(View view){
final String userName = editText_userName.getText().toString();
if (TextUtils.isEmpty(userName)){
textView_info.setText("用户名不能为空");
return;
}
final String passWord = editText_passWord.getText().toString();
if (TextUtils.isEmpty(passWord)){
textView_info.setText("密码不能为空");
return;
}
// 启动登陆工作线程
new Thread(new Runnable() {
@Override
public void run() {
// 接口地址
String path= "http://192.168.1.114/login.php";
// String path= "http://192.168.1.40/login.php";
try {
URL url = new URL(path);
// 打开http链接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setConnectTimeout(1000*30); // 连接超时时间
conn.setReadTimeout(1000*30); // 读取数据超时时间
conn.setUseCaches(false);
conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
// 对服务器端读取或者写入数据(使用输入输出流)
// 获取连接的输出流
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
// action=login 表示登陆 也可以等于别的 主要看你的php同事如何协商
// 一般来说 action=login 表示登陆 action=update 表示修改密码 不多赘述
// 接口php同事怎么写你就怎么传
dos.writeBytes("action="+ URLEncoder.encode("login","UTF8"));
dos.writeBytes("&username="+ URLEncoder.encode(userName,"UTF8"));
dos.writeBytes("&password="+ URLEncoder.encode(passWord,"UTF8"));
dos.flush();
dos.close();
// 从服务器获取相应数据
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String result = br.readLine();
System.out.println("result == " + result);
br.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
}
至此,可以AndroidStudio的控制台查看的服务器返回的结果,但是没有显示到UI上面,下一篇博文,我们把服务器的结果显示在UI上。
调试信息:
04-25 03:12:44.886 5373-7416/com.iwanghang.httpurlconnectiondemo I/System.out: result == {"login":"iwanghang---123---success"}04-25 03:12:46.589 5373-7446/com.iwanghang.httpurlconnectiondemo I/System.out: result == {"login":"\u8d26\u6237\u540d\u6216\u5bc6\u7801\u64cd\u4f5c"}
不要忘记访问网络的权限:
<uses-permission android:name="android.permission.INTERNET"/>----------
MainActivity.java:(使用handler设置textView_info)
package com.iwanghang.httpurlconnectiondemo;import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.ref.WeakReference;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
public class MainActivity extends AppCompatActivity {
private TextView textView_info;
private EditText editText_userName;
private EditText editText_passWord;
private final MyHandler myHandler = new MyHandler(this);
private static final int LOAD_SUCESS = 0x1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView_info = (TextView) findViewById(R.id.textView_info);
editText_userName = (EditText) findViewById(R.id.editText_userName);
editText_passWord = (EditText) findViewById(R.id.editText_passWord);
}
public void loginClick(View view){
final String userName = editText_userName.getText().toString();
if (TextUtils.isEmpty(userName)){
textView_info.setText("用户名不能为空");
return;
}
final String passWord = editText_passWord.getText().toString();
if (TextUtils.isEmpty(passWord)){
textView_info.setText("密码不能为空");
return;
}
// 启动登陆工作线程
new Thread(new Runnable() {
@Override
public void run() {
// 接口地址
String path= "http://192.168.1.114/login.php";
// String path= "http://192.168.1.40/login.php";
try {
URL url = new URL(path);
// 打开http链接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setConnectTimeout(1000*30); // 连接超时时间
conn.setReadTimeout(1000*30); // 读取数据超时时间
conn.setUseCaches(false);
conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
// 对服务器端读取或者写入数据(使用输入输出流)
// 获取连接的输出流
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
// action=login 表示登陆 也可以等于别的 主要看你的php同事如何协商
// 一般来说 action=login 表示登陆 action=update 表示修改密码 不多赘述
// 接口php同事怎么写你就怎么传
dos.writeBytes("action="+ URLEncoder.encode("login","UTF8"));
dos.writeBytes("&username="+ URLEncoder.encode(userName,"UTF8"));
dos.writeBytes("&password="+ URLEncoder.encode(passWord,"UTF8"));
dos.flush();
dos.close();
// 从服务器获取相应数据
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String result = br.readLine();
System.out.println("result == " + result);
br.close();
conn.disconnect();
// 通过handler把result传出去
Message msg = myHandler.obtainMessage(LOAD_SUCESS,result);
myHandler.sendMessage(msg);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
private static class MyHandler extends Handler {
private final WeakReference<MainActivity> weakReference; // 软引用
public MyHandler(MainActivity mainActivity){
weakReference = new WeakReference<MainActivity>(mainActivity);
}
@Override
public void handleMessage(Message msg) {
MainActivity mainActivity = weakReference.get();
if (mainActivity!=null){
switch (msg.what){
case LOAD_SUCESS:
mainActivity.textView_info.setText((String)msg.obj); // 获取msg 设置UI显示
break;
}
}
}
}
}
转载请注明出处:http://blog.csdn.net/iwanghang/article/details/70685334
欢迎移动开发爱好者交流
沈阳或周边城市公司有意开发Android,请与我联系
联系方式
微信:iwanghang
QQ:413711276
邮箱:iwanghang@qq.com
觉得博文有用,请点赞,请评论,请关注,谢谢!~
相关文章推荐
- Android开发-基础网络组件(1)使用HttpURLConnection登陆-注意打开网络需要在线程中执行-主线程不支持
- Android开发-基础网络组件(2)使用ApacheHttpClient登陆-AndroidStudio
- Android App开发基础篇—HttpURLConnection基础使用
- 10_Android中通过HttpUrlConnection访问网络,Handler和多线程使用,读取网络html代码并显示在界面上,ScrollView组件的使用
- Android开发-高级网络组件(1)使用Volley登陆-AndroidStudio
- 10_Android中通过HttpUrlConnection访问网络,Handler和多线程使用,读取网络html代码并显示在界面上,ScrollView组件的使用
- Android开发使用HttpURLConnection进行网络编程详解【附源码下载】
- [Android基础]Android中使用HttpURLConnection
- Android的网络应用-使用HttpURLConnection
- Android访问网络,使用HttpURLConnection还是HttpClient
- Android访问网络 使用HttpURLConnection还是HttpClient?
- 【Android开发那点破事】解决Andriod使用HttpURLConnection 失败问题
- Android访问网络,使用HttpURLConnection还是HttpClient?
- Android访问网络,使用HttpURLConnection还是HttpClient?
- Android访问网络,使用HttpURLConnection还是HttpClient?
- Android开发之使用HttpURLConnection进行POST请求
- Android之使用HttpURLConnection进行网络访问
- Android访问网络,使用HttpURLConnection还是HttpClient?
- Android初级开发(九)——网络交互—HttpURLConnection
- HTTP基础与Android之——使用HttpClient和HttpURLConnection