标签:android应用 网络编程
1.客户端功能
客户端程序模拟App用户注册过程:
用户点击注册按钮后,客户端会通过HTTP协议向服务器发送POST请求/GET请求并传送数据,服务器获得数据后进行相关数据库处理,然后服务器再将处理的结果作为响应返回给客户端,客户端根据获得的响应信息继续处理业务逻辑。
2.源码结构
(1)LoginActivity.java:客户端界面(UI),在子线程内通过消息机制完成向服务器发送请求,接收并处理响应信息;
(2)personalActivity.java:用户界面(UI),当用户注册成功后(即HTTP通信成功),客户端跳转至该界面;
(3)LoginToSever.java:客户端与服务器通信的实际实现类,包括发送请求、获取响应信息;
3.源码实现
(1)LoginActivity.java:客户端界面,在子线程内通过消息机制完成向服务器发送请求,接收并处理响应信息;
- package com.example.http_client;
- 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.Toast;
-
- /*通过子进程、消息传递机制,完成HTTP网络通信*/
- public class LoginActivity extends Activity {
- private EditText userName;
- private EditText password;
- private EditText confirmPsd;
- private Button registerBtn;
- private Button resetBtn;
- private void init()
- {
- userName = (EditText)findViewById(R.id.uername);
- password= (EditText)findViewById(R.id.password);
- confirmPsd=(EditText)findViewById(R.id.confirm);
- registerBtn= (Button)findViewById(R.id.register);
- resetBtn=(Button)findViewById(R.id.reset);
- }
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- init(); //初始化控件
- this.registerBtn.setOnClickListener(new OnClickListener() {
- public void onClick(View v) {
- //1.创建一个Handler类对象,并重写handleMessage()方法
- final Handler myHandler=new Handler(){
- public void handleMessage(Message msg) {
- String response=(String)msg.obj; //读取obj发送过来的消息
- if("true".equals(response))
- {
- Intent intent=new Intent();
- intent.setClass(LoginActivity.this, personalActivity.class);
- startActivity(intent);
- }
- else
- {
- Toast.makeText(LoginActivity.this, "用户名与密码不对!",Toast.LENGTH_SHORT).show();
- }
- }
- };
- //2.创建一个子线程
- new Thread(new Runnable(){
- public void run() {
- LoginToServer login = new LoginToServer();
- String result=login.doPost(userName.getText().toString(), password.getText().toString());
-
- System.out.println(result); //调试:打印服务器返回的结果,测试是否通信成功
-
- Message msg=new Message();
- msg.obj=result; //将响应信息保存到obj中
- myHandler.sendMessage(msg);
- }
- }).start();
- }
- });
- }
- }
(2)personalActivity.java:用户界面(UI),当用户注册成功后(即HTTP通信成功),客户端跳转至该界面;
- package com.example.http_client;
-
- import android.app.Activity;
- import android.os.Bundle;
-
- public class personalActivity extends Activity {
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.personal);
- }
-
- }
(3)LoginToSever.java:(POST请求)客户端与服务器通信的实际实现类,包括发送请求、获取响应信息;
- package com.example.http_client;
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.InputStreamReader;
- import java.io.UnsupportedEncodingException;
- import java.util.ArrayList;
- import java.util.List;
- import org.apache.http.HttpEntity;
- import org.apache.http.HttpResponse;
- import org.apache.http.HttpStatus;
- import org.apache.http.NameValuePair;
- import org.apache.http.client.ClientProtocolException;
- import org.apache.http.client.HttpClient;
- import org.apache.http.client.entity.UrlEncodedFormEntity;
- import org.apache.http.client.methods.HttpPost;
- import org.apache.http.impl.client.DefaultHttpClient;
- import org.apache.http.message.BasicNameValuePair;
-
- public class LoginToServer {
- private String url="http://10.0.2.2:8080/login/LoginServlet";
//访问服务器资源的URL地址
- // private String url="http://localhost:8080/login/LoginServlet";
- String result="";
-
- /*doPost方法:
- * 作用:实现客户端向服务器发送POST请求*/
- public String doPost(String name,String psd)
- {
- HttpClient hc=new DefaultHttpClient(); //a.创建HttpClient对象
- HttpPost httpPost=new HttpPost(url); //b.根据URL地址创建HttpPost对象
- NameValuePair param1= new BasicNameValuePair("username",name);
- NameValuePair param2=new BasicNameValuePair("psd",psd);
- // System.out.println("username="+name+"psd="+psd);
- List<NameValuePair> params = new ArrayList<NameValuePair>();
- params.add(param1);
- params.add(param2); //c.创建参数列表,每个参数以键值对的形式且保存在NameValuePair中
- HttpEntity he;
- try {
- he = new UrlEncodedFormEntity(params,"GBK"); //d.根据参数创建HttpEntity对象
- httpPost.setEntity(he); //e.将HttpEntity对象赋给HttpPost对象
- HttpResponse response = hc.execute(httpPost); //f.执行HttpClient的execute()方法获取HttpResponse对象
- if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
- {
- HttpEntity het = response.getEntity(); //g.执行HttpResponse的getEntity方法,获取HttpEntity对象
- InputStream is= het.getContent(); //h.执行HttpEntity的getContent方法,获取对应的输入流
- BufferedReader br = new BufferedReader(new InputStreamReader(is));
- //i.读取输入流中的内容,并以字符串的形式返回
- String readLine = null;
- while((readLine = br.readLine()) != null )
- {
- result=result+readLine;
- }
- is.close();
- }
- else
- {
- result="error";
- }
- } catch (IOException e) {
- e.printStackTrace();
- // System.out.println(e.getMessage()); //调试:打印异常日志
- result="Exception";
- }
-
- return result;//返回服务器响应传递回来的结果
- }
- }
(4)AndroidMainfest.xml:修改配置清单文件
◆添加网络访问权限(重要): <uses-permission android:name="android.permission.INTERNET"></uses-permission>
◆注册personActivity组件:<activity android:name=".personalActivity" >
- <?xml version="1.0" encoding="utf-8"?>
- <manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.example.http_client"
- android:versionCode="1"
- android:versionName="1.0" >
- <uses-permission android:name="android.permission.INTERNET"></uses-permission>
- <uses-sdk
- android:minSdkVersion="8"
- android:targetSdkVersion="21" />
-
- <application
- android:allowBackup="true"
- android:icon="@drawable/ic_launcher"
- android:label="@string/app_name"
- android:theme="@style/AppTheme" >
- <activity
- android:name=".LoginActivity"
- android:label="@string/app_name" >
- <intent-filter>
- <action android:name="android.intent.action.MAIN" />
-
- <category android:name="android.intent.category.LAUNCHER" />
- </intent-filter>
- </activity>
-
- <activity android:name=".personalActivity" >
- </activity>
- </application>
-
- </manifest>
4.注意事项
(1)Tomcat已启动,并且Java Web程序已部署到Tomcat服务器中;
(2)客户端访问服务端的URL要正确,在此为http://10.0.2.2:8080/login/LoginServlet而不是Java Web中的http://localhost:8080/login/LoginServlet。因为模拟机通过127.0.0.1访问的是模拟器本身。在模拟器上访问安装模拟器的电脑,需要使用android内置的IP:10.0.2.2。10.0.2.2
是模拟器设置的特定ip,是你的电脑的别名,如果是网络服务器,可直接写相应的IP或网址;
(3)需要在清单文件中添加访问网络的权限;
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
(4)不能直接访问网络,需进行相应处理,建议采用消息传递机制;
02.HTTP协议之客户端实现(POST请求)
标签:android应用 网络编程
原文地址:http://blog.csdn.net/u012637501/article/details/45149145