02.HTTP协议之客户端实现(POST请求)
- 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();
- }
- });
- }
- }
- 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);
- }
- }
- 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;//返回服务器响应传递回来的结果
- }
- }
- <?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>
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。