栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Day27-Http实现客户端登录网站案例

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Day27-Http实现客户端登录网站案例

文章目录
    • 题目
    • 效果图
    • ‍一、开发主页面MainActivity
      • 1.编写主页布局activity_main.xml
      • 2.编写主页MainActivity.java
    • ‍二、开发LoginOkActivity页面
      • 1.编写activity_login_ok.xml
      • 2.编写LoginOkActivity.java

题目
使用HttpURLConnection组件或者OkHttp组件模拟登录网站,并读取其中一些数据展示出来
效果图


‍一、开发主页面MainActivity 1.编写主页布局activity_main.xml

    

        
    

    

    

        

            
        

        

        
2.编写主页MainActivity.java
package com.example.week10homework;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;


public class MainActivity extends Activity {

	Button okBtn;
	EditText userNameET,pwdET;
	TextView tipTV;
	//食乐网登录地址
	String path = "http://www.sl777.cc/API/DataM/SQLData/userLogin";

	Handler handler = new Handler(){
		public void handleMessage(Message msg){
			if(msg.what==1){
				String userInfo = String.valueOf(msg.obj);
				JSONObject jo = (JSONObject) JSON.parse(userInfo);
				String joData = jo.getString("data");
				if("".equals(joData) ||"[]".equals(joData)){
					tipTV.setText("用户名或密码错误,登陆失败!");
				}else {
					Intent intent = new Intent(MainActivity.this, LoginOkActivity.class);
					intent.putExtra("userInfo", userInfo);
					startActivity(intent);
				}
			}else if(msg.what==0){
				tipTV.setText(String.valueOf(msg.obj));
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		userNameET  = (EditText)findViewById(R.id.c103userName);
		pwdET = (EditText)findViewById(R.id.c103pwd);
		okBtn= (Button)findViewById(R.id.c103okBtn);
		tipTV =(TextView)findViewById(R.id.c103tipTV);


		okBtn.getBackground().setAlpha(100);

		okBtn.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View arg0) {
				final String userName = userNameET.getText().toString();
				final String pwd = pwdET.getText().toString();
				userNameET.setText("");
				pwdET.setText("");
				tipTV.setText("");
				if(userName.equals("")||pwd.equals("")){
					Toast.makeText(MainActivity.this, "用户名和密码不能为空", Toast.LENGTH_SHORT).show();
					return ;
				}
				Runnable runnable =new Runnable(){
					public void run(){
						try{
							URL url = new URL(path);
							HttpURLConnection connection = (HttpURLConnection) url.openConnection();
							connection.setRequestMethod("POST");//设置请求方式为POST
							connection.setDoOutput(true);//允许写出
							connection.setDoInput(true);//允许读入
							connection.setUseCaches(false);//不使用缓存
							connection.connect();
							String body = "Param={'where':'account="+userName+" and password="+pwd+"'}";
							BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream(), "UTF-8"));
							writer.write(body);
							writer.close();

							int responseCode = connection.getResponseCode();
							if(responseCode == HttpURLConnection.HTTP_OK){
								InputStream inputStream = connection.getInputStream();
								String entityStr = is2String(inputStream);//将流转换为字符串
								Message msg = Message.obtain(handler, 1, entityStr);
								msg.sendToTarget();
							}else{
								Message msg = Message.obtain(handler, 0, "网络连接异常");
								msg.sendToTarget();
							}

						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				};

				new Thread(runnable).start();
			}
		});
	}


	public String is2String(InputStream is) throws IOException{

		//连接后,创建一个输入流来读取response
		BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is,"utf-8"));
		String line = "";
		StringBuilder stringBuilder = new StringBuilder();
		//每次读取一行,若非空则添加至 stringBuilder
		while((line = bufferedReader.readLine()) != null){
			stringBuilder.append(line);
		}
		//读取所有的数据后,赋值给 response;
		String result = stringBuilder.toString().trim();
		return result;
	}
}


‍二、开发LoginOkActivity页面 1.编写activity_login_ok.xml

    

        
    

    
    
    
    






2.编写LoginOkActivity.java
package com.example.week10homework;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.week10homework.R;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;


public class LoginOkActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login_ok);

		TextView userInfoTV = (TextView)findViewById(R.id.c103userInfo);
		TextView srcInfoTV = (TextView)findViewById(R.id.c103srcInfo);

		Intent intent=this.getIntent();
		Bundle bundle = intent.getExtras();
		String userInfo = bundle.getString("userInfo");
		JSONObject jo = (JSONObject) JSON.parse(userInfo);
		JSONObject userJo =(JSONObject)jo.getJSONArray("data").get(0);
		StringBuffer sb = new StringBuffer();
		sb.append("账号:").append(userJo.getString("account")).append("n");
		sb.append("密码:").append(userJo.getString("password")).append("n");
		sb.append("电话:").append(userJo.getString("telephone")).append("n");
		sb.append("昵称:").append(userJo.getString("nickName")).append("n");
		sb.append("创建时间:").append(userJo.getString("createTime"));
		userInfoTV.setText(sb.toString());
		srcInfoTV.setText(userInfo);

	}
	
	
	
	

}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/854492.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号