12_Android中HttpClient的应用,doGet,doPost,doHttpClientGet,doHttpClient请求,另外借助第三方框架实现网络连接的应用,

简介: 准备条件,编写一个web项目。编写一个servlet,若用户名为lisi,密码为123,则返回“登录成功”,否则”登录失败”。项目名为ServerItheima28。代码如下: package com.itheima28.servlet;   import java.io.IOException; import java.io.PrintWriter;

  1. 准备条件,

  1. 编写一个web项目。编写一个servlet,若用户名为lisi,密码为123,则返回登录成功,否则登录失败。项目名为ServerItheima28。代码如下:

package com.itheima28.servlet;

 

import java.io.IOException;

import java.io.PrintWriter;

 

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

 

public class LoginServlet extends HttpServlet {

 

         /**

          * The doGet method of the servlet. <br>

          *

          * This method is called when a form has its tag value method equals to get.

          *

          * @param request the request send by the client to the server

          * @param response the response send by the server to the client

          * @throws ServletException if an error occurred

          * @throws IOException if an error occurred

          */

         public void doGet(HttpServletRequest request, HttpServletResponse response)

                            throws ServletException, IOException {

                   String username = request.getParameter("username");       // 采用的编码是: iso-8859-1

                   String password = request.getParameter("password");

                  

                   // 采用iso8859-1的编码对姓名进行逆转, 转换成字节数组, 再使用utf-8编码对数据进行转换, 字符串

                   username = new String(username.getBytes("iso8859-1"), "utf-8");

                   password = new String(password.getBytes("iso8859-1"), "utf-8");

                  

                   System.out.println("姓名: " + username);

                   System.out.println("密码: " + password);

                  

                   if("lisi".equals(username) && "123".equals(password)) {

                            /*

                             * getBytes 默认情况下, 使用的iso8859-1的编码, 但如果发现码表中没有当前字符,

                             * 会使用当前系统下的默认编码: GBK

                             */

                            response.getOutputStream().write("登录成功".getBytes("utf-8"));

                   } else {

                            response.getOutputStream().write("登录失败".getBytes("utf-8"));

                   }

         }

 

         /**

          * The doPost method of the servlet. <br>

          *

          * This method is called when a form has its tag value method equals to post.

          *

          * @param request the request send by the client to the server

          * @param response the response send by the server to the client

          * @throws ServletException if an error occurred

          * @throws IOException if an error occurred

          */

         public void doPost(HttpServletRequest request, HttpServletResponse response)

                            throws ServletException, IOException {

                   System.out.println("doPost");

                   doGet(request, response);

         }

 

}

 

  1. 使用github上的android-async-http-master框架:

2 编写Android应用,应用截图如下:

代码结构如下:

清单文件

<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

    package="com.itheim28.submitdata"

    android:versionCode="1"

    android:versionName="1.0" >

 

    <uses-sdk

        android:minSdkVersion="8"

        android:targetSdkVersion="19" />

    <uses-permission android:name="android.permission.INTERNET"/>

 

    <application

        android:allowBackup="true"

        android:icon="@drawable/ic_launcher"

        android:label="@string/app_name"

        android:theme="@style/AppTheme" >

        <activity

            android:name="com.itheim28.submitdata.MainActivity"

            android:label="@string/app_name" >

            <intent-filter>

                <action android:name="android.intent.action.MAIN" />

 

                <category android:name="android.intent.category.LAUNCHER" />

            </intent-filter>

        </activity>

    </application>

 

</manifest>

3  编写布局文件activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:orientation="vertical"

    tools:context=".MainActivity" >

 

    <EditText

        android:id="@+id/et_username"

        android:layout_width="fill_parent"

        android:layout_height="wrap_content"

        android:hint="请输入姓名" />

 

    <EditText

        android:id="@+id/et_password"

        android:layout_width="fill_parent"

        android:layout_height="wrap_content"

        android:hint="请输入密码" />

 

    <Button

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:onClick="doGet"

        android:text="Get方式提交" />

 

    <Button

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:onClick="doPost"

        android:text="Post方式提交" />

   

    <Button

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:onClick="doHttpClientOfGet"

        android:text="使用HttpClient方式提交Get请求" />

 

    <Button

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:onClick="doHttpClientOfPost"

        android:text="使用HttpClient方式提交Post请求" />

</LinearLayout>

4 NetUtils的内容如下:

package com.itheim28.submitdata.utils;

 

import java.io.ByteArrayOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

import java.net.HttpURLConnection;

import java.net.URL;

import java.net.URLEncoder;

 

import android.util.Log;

 

public class NetUtils {

 

         private static final String TAG = "NetUtils";

 

         /**

          * 使用post的方式登录

          *

          * @param userName

          * @param password

          * @return

          */

         public static String loginOfPost(String userName, String password) {

                   HttpURLConnection conn = null;

                   try {

                            URL url = new URL(

                                              "http://114.215.142.191:8080/ServerItheima28/servlet/LoginServlet");

 

                            conn = (HttpURLConnection) url.openConnection();

 

                            conn.setRequestMethod("POST");

                            conn.setConnectTimeout(10000); // 连接的超时时间

                            conn.setReadTimeout(5000); // 读数据的超时时间

                            conn.setDoOutput(true); // 必须设置此方法, 允许输出

                            // conn.setRequestProperty("Content-Length", 234); // 设置请求头消息,

                            // 可以设置多个

 

                            // post请求的参数

                            String data = "username=" + userName + "&password=" + password;

 

                            // 获得一个输出流, 用于向服务器写数据, 默认情况下, 系统不允许向服务器输出内容

                            OutputStream out = conn.getOutputStream();

                            out.write(data.getBytes());

                            out.flush();

                            out.close();

 

                            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;

         }

 

         /**

          * 使用get的方式登录

          *

          * @param userName

          * @param password

          * @return 登录的状态

          */

         public static String loginOfGet(String userName, String password) {

                   HttpURLConnection conn = null;

                   try {

                            String data = "username=" + URLEncoder.encode(userName)

                                               + "&password=" + URLEncoder.encode(password);

                            URL url = new URL(

                                               "http://114.215.142.191:8080/ServerItheima28/servlet/LoginServlet?"

                                                                 + data);

                            conn = (HttpURLConnection) url.openConnection();

 

                            conn.setRequestMethod("GET"); // get或者post必须得全大写

                            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;

         }

 

         /**

          * 根据流返回一个字符串信息

          *

          * @param is

          * @return

          * @throws IOException

          */

         private 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);

                   }

                   is.close();

 

                   String html = baos.toString(); // 把流中的数据转换成字符串, 采用的编码是: utf-8

 

                   // String html = new String(baos.toByteArray(), "GBK");

 

                   baos.close();

                   return html;

         }

}

5 NetUtils2代码如下:

package com.itheim28.submitdata.utils;

 

import java.io.ByteArrayOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.util.ArrayList;

import java.util.List;

 

import org.apache.http.HttpResponse;

import org.apache.http.NameValuePair;

import org.apache.http.client.HttpClient;

import org.apache.http.client.entity.UrlEncodedFormEntity;

import org.apache.http.client.methods.HttpGet;

import org.apache.http.client.methods.HttpPost;

import org.apache.http.impl.client.DefaultHttpClient;

import org.apache.http.message.BasicNameValuePair;

 

import android.util.Log;

 

public class NetUtils2 {

 

         private static final String TAG = "NetUtils";

 

         /**

          * 使用post的方式登录

          *

          * @param userName

          * @param password

          * @return

          */

         public static String loginOfPost(String userName, String password) {

                   HttpClient client = null;

                   try {

                            // 定义一个客户端

                            client = new DefaultHttpClient();

 

                            // 定义post方法

                            HttpPost post = new HttpPost(

                                              "http://114.215.142.191:8080/ServerItheima28/servlet/LoginServlet");

 

                            // 定义post请求的参数

                            List<NameValuePair> parameters = new ArrayList<NameValuePair>();

                            parameters.add(new BasicNameValuePair("username", userName));

                            parameters.add(new BasicNameValuePair("password", password));

 

                            // post请求的参数包装了一层.

 

                            // 不写编码名称服务器收数据时乱码. 需要指定字符集为utf-8

                            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters,

                                               "utf-8");

                            // 设置参数.

                            post.setEntity(entity);

 

                            // 设置请求头消息

                            // post.addHeader("Content-Length", "20");

 

                            // 使用客户端执行post方法

                            HttpResponse response = client.execute(post); // 开始执行post请求,

                                                                                                                                            // 会返回给我们一个HttpResponse对象

 

                            // 使用响应对象, 获得状态码, 处理内容

                            int statusCode = response.getStatusLine().getStatusCode(); // 获得状态码

                            if (statusCode == 200) {

                                     // 使用响应对象获得实体, 获得输入流

                                     InputStream is = response.getEntity().getContent();

                                     String text = getStringFromInputStream(is);

                                      return text;

                            } else {

                                     Log.i(TAG, "请求失败: " + statusCode);

                            }

                   } catch (Exception e) {

                            e.printStackTrace();

                   } finally {

                            if (client != null) {

                                     client.getConnectionManager().shutdown(); // 关闭连接和释放资源

                            }

                   }

                   return null;

         }

 

         /**

          * 使用get的方式登录

          *

          * @param userName

          * @param password

          * @return 登录的状态

          */

         public static String loginOfGet(String userName, String password) {

                   HttpClient client = null;

                   try {

                            // 定义一个客户端

                            client = new DefaultHttpClient();

 

                            // 定义一个get请求方法

                            String data = "username=" + userName + "&password=" + password;

                            HttpGet get = new HttpGet(

                                               "http://114.215.142.191:8080/ServerItheima28/servlet/LoginServlet?" + data);

 

                            // response 服务器相应对象, 其中包含了状态信息和服务器返回的数据

                            // 开始执行get方法, 请求网络

                            HttpResponse response = client.execute(get);

 

                            // 获得响应码

                            int statusCode = response.getStatusLine().getStatusCode();

 

                            if (statusCode == 200) {

                                     InputStream is = response.getEntity().getContent();

                                     String text = getStringFromInputStream(is);

                                     return text;

                            } else {

                                     Log.i(TAG, "请求失败: " + statusCode);

                            }

                   } catch (Exception e) {

                            e.printStackTrace();

                   } finally {

                            if (client != null) {

                                     client.getConnectionManager().shutdown(); // 关闭连接, 和释放资源

                            }

                   }

                   return null;

         }

 

         /**

          * 根据流返回一个字符串信息

          *

          * @param is

          * @return

          * @throws IOException

          */

         private 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);

                   }

                   is.close();

 

                   String html = baos.toString(); // 把流中的数据转换成字符串, 采用的编码是: utf-8

 

                   // String html = new String(baos.toByteArray(), "GBK");

 

                   baos.close();

                   return html;

         }

}

6 MainActivity代码如下:

package com.itheim28.submitdata;

 

import android.app.Activity;

import android.os.Bundle;

import android.text.TextUtils;

import android.util.Log;

import android.view.View;

import android.widget.EditText;

import android.widget.Toast;

 

import com.itheim28.submitdata.utils.NetUtils;

import com.itheim28.submitdata.utils.NetUtils2;

 

public class MainActivity extends Activity {

 

         private static final String TAG = "MainActivity";

         private EditText etUserName;

         private EditText etPassword;

 

         @Override

         protected void onCreate(Bundle savedInstanceState) {

                   super.onCreate(savedInstanceState);

                   setContentView(R.layout.activity_main);

 

                   etUserName = (EditText) findViewById(R.id.et_username);

                   etPassword = (EditText) findViewById(R.id.et_password);

         }

 

         /**

          * 使用httpClient方式提交get请求

          *

          * @param v

          */

         public void doHttpClientOfGet(View v) {

                   Log.i(TAG, "doHttpClientOfGet");

                   final String userName = etUserName.getText().toString();

                   final String password = etPassword.getText().toString();

 

                   new Thread(new Runnable() {

 

                            @Override

                            public void run() {

                                     // 请求网络

                                     final String state = NetUtils2.loginOfGet(userName, password);

                                     // 执行任务在主线程中

                                     runOnUiThread(new Runnable() {

                                               @Override

                                               public void run() {

                                                        // 就是在主线程中操作

                                                        Toast.makeText(MainActivity.this, state, 0).show();

                                               }

                                     });

                            }

                   }).start();

         }

 

         /**

          * 使用httpClient方式提交post请求

          *

          * @param v

          */

         public void doHttpClientOfPost(View v) {

                   Log.i(TAG, "doHttpClientOfPost");

                   final String userName = etUserName.getText().toString();

                   final String password = etPassword.getText().toString();

 

                   new Thread(new Runnable() {

                            @Override

                            public void run() {

                                     final String state = NetUtils2.loginOfPost(userName, password);

                                     // 执行任务在主线程中

                                     runOnUiThread(new Runnable() {

                                               @Override

                                               public void run() {

                                                        // 就是在主线程中操作

                                                        Toast.makeText(MainActivity.this, state, 0).show();

                                               }

                                     });

                            }

                   }).start();

         }

 

         public void doGet(View v) {

                   final String userName = etUserName.getText().toString();

                   final String password = etPassword.getText().toString();

 

                   new Thread(new Runnable() {

 

                            @Override

                            public void run() {

                                     // 使用get方式抓去数据

                                     final String state = NetUtils.loginOfGet(userName, password);

 

                                     // 执行任务在主线程中

                                     runOnUiThread(new Runnable() {

                                               @Override

                                               public void run() {

                                                        // 就是在主线程中操作

                                                        Toast.makeText(MainActivity.this, state, 0).show();

                                               }

                                     });

                            }

                   }).start();

         }

 

         public void doPost(View v) {

                   final String userName = etUserName.getText().toString();

                   final String password = etPassword.getText().toString();

 

                   new Thread(new Runnable() {

                            @Override

                            public void run() {

                                     final String state = NetUtils.loginOfPost(userName, password);

                                     // 执行任务在主线程中

                                     runOnUiThread(new Runnable() {

                                               @Override

                                               public void run() {

                                                        // 就是在主线程中操作

                                                        Toast.makeText(MainActivity.this, state, 0).show();

                                               }

                                     });

                            }

                   }).start();

         }

}

7 MainActivity2 的代码如下:

package com.itheim28.submitdata;

 

import java.net.URLEncoder;

 

import org.apache.http.Header;

 

import android.app.Activity;

import android.os.Bundle;

import android.view.View;

import android.widget.EditText;

import android.widget.Toast;

 

import com.loopj.android.http.AsyncHttpClient;

import com.loopj.android.http.AsyncHttpResponseHandler;

import com.loopj.android.http.RequestParams;

 

public class MainActivity2 extends Activity {

 

    protected static final String TAG = "MainActivity2";

    private EditText etUserName;

    private EditText etPassword;

 

    @Override

    protected void onCreate(Bundle savedInstanceState) {

       super.onCreate(savedInstanceState);

       setContentView(R.layout.activity_main);

 

       etUserName = (EditText) findViewById(R.id.et_username);

       etPassword = (EditText) findViewById(R.id.et_password);

    }

 

    public void doGet(View v) {

       final String userName = etUserName.getText().toString();

       final String password = etPassword.getText().toString();

 

       AsyncHttpClient client = new AsyncHttpClient();

 

       String data = "username=" + URLEncoder.encode(userName) + "&password="

              + URLEncoder.encode(password);

 

        client.get("http://114.215.142.191:8080/ServerItheima28/servlet/LoginServlet?"

              + data, new MyResponseHandler());

    }

 

    public void doPost(View v) {

       final String userName = etUserName.getText().toString();

       final String password = etPassword.getText().toString();

 

       AsyncHttpClient client = new AsyncHttpClient();

 

       RequestParams params = new RequestParams();

       params.put("username", userName);

       params.put("password", password);

 

       client.post(

               "http://114.215.142.191:8080/ServerItheima28/servlet/LoginServlet",

              params, new MyResponseHandler());

    }

 

    class MyResponseHandler extends AsyncHttpResponseHandler {

 

       @Override

       public void onSuccess(int statusCode, Header[] headers,

              byte[] responseBody) {

           // Log.i(TAG, "statusCode: " + statusCode);

 

           Toast.makeText(

                  MainActivity2.this,

                  "成功: statusCode: " + statusCode + ", body: "

                         + new String(responseBody), 0).show();

       }

 

       @Override

       public void onFailure(int statusCode, Header[] headers,

              byte[] responseBody, Throwable error) {

           Toast.makeText(MainActivity2.this, "失败: statusCode: " + statusCode,

                  0).show();

       }

    }

}

 

 

 

 

 

 

 

 

 

 

 

 

 

目录
相关文章
|
1月前
|
IDE Java 开发工具
深入探索安卓应用开发:从环境搭建到第一个"Hello, World!"应用
本文将引导读者完成安卓应用开发的初步入门,包括安装必要的开发工具、配置开发环境、创建第一个简单的安卓项目,以及解释其背后的一些基本概念。通过一步步的指导和解释,本文旨在为安卓开发新手提供一个清晰、易懂的起点,帮助读者顺利地迈出安卓开发的第一步。
205 65
|
1月前
|
存储 Java Android开发
探索安卓应用开发:构建你的第一个"Hello World"应用
【9月更文挑战第24天】在本文中,我们将踏上一段激动人心的旅程,深入安卓应用开发的奥秘。通过一个简单而经典的“Hello World”项目,我们将解锁安卓应用开发的基础概念和步骤。无论你是编程新手还是希望扩展技能的老手,这篇文章都将为你提供一次实操体验。从搭建开发环境到运行你的应用,每一步都清晰易懂,确保你能顺利地迈出安卓开发的第一步。让我们开始吧,探索如何将一行简单的代码转变为一个功能齐全的安卓应用!
|
6天前
|
调度 Android开发 开发者
构建高效Android应用:探究Kotlin多线程优化策略
【10月更文挑战第11天】本文探讨了如何在Kotlin中实现高效的多线程方案,特别是在Android应用开发中。通过介绍Kotlin协程的基础知识、异步数据加载的实际案例,以及合理使用不同调度器的方法,帮助开发者提升应用性能和用户体验。
22 4
|
6天前
|
编解码 Android开发 UED
构建高效Android应用:从内存优化到用户体验
【10月更文挑战第11天】本文探讨了如何通过内存优化和用户体验改进来构建高效的Android应用。介绍了使用弱引用来减少内存占用、懒加载资源以降低启动时内存消耗、利用Kotlin协程进行异步处理以保持UI流畅,以及采用响应式设计适配不同屏幕尺寸等具体技术手段。
21 2
|
16天前
|
JSON API Android开发
探索安卓开发之旅:打造你的第一个天气应用
在这篇文章中,我们将一起踏上一段激动人心的旅程,学习如何在安卓平台上开发一个简单的天气应用。通过实际操作和代码示例,我们将逐步构建一个能够显示当前位置天气情况的应用。无论你是编程新手还是有一定经验的开发者,这篇文章都将为你提供清晰的指导和启发性的见解,帮助你理解和掌握安卓开发的基础知识。让我们一起探索代码的世界,解锁新技能,实现你的创意和梦想。
|
19天前
|
安全 Java API
Java 泛型在安卓开发中的应用
在Android开发中,Java泛型广泛应用于集合类、自定义泛型类/方法、数据绑定、适配器及网络请求等场景,有助于实现类型安全、代码复用和提高可读性。例如,结合`ArrayList`使用泛型可避免类型转换错误;自定义泛型类如`ApiResponse&lt;T&gt;`可处理不同类型API响应;RecyclerView适配器利用泛型支持多种视图数据;Retrofit结合泛型定义响应模型,明确数据类型。然而,需注意类型擦除导致的信息丢失问题。合理使用泛型能显著提升代码质量和应用健壮性。
|
15天前
|
XML 数据可视化 Android开发
Android应用界面
Android应用界面中的布局和控件使用,包括相对布局、线性布局、表格布局、帧布局、扁平化布局等,以及AdapterView及其子类如ListView的使用方法和Adapter接口的应用。
11 0
Android应用界面
|
1月前
|
开发框架 搜索推荐 开发工具
打造个性化安卓应用:从零开始的Flutter之旅
【8月更文挑战第51天】本文是一篇面向初学者的Flutter入门教程,旨在通过简单易懂的语言和实际代码示例,引导读者步入跨平台移动应用开发的世界。文章首先介绍了Flutter的基本概念和优势,然后逐步展示了如何搭建开发环境、创建第一个Flutter应用,并实现了一个简单的待办事项列表。最后,文章探讨了Flutter在实现高性能和美观界面方面的潜力,鼓励读者发挥创意,探索更多可能。
79 15
|
27天前
|
监控 安全 Java
Kotlin 在公司上网监控中的安卓开发应用
在数字化办公环境中,公司对员工上网行为的监控日益重要。Kotlin 作为一种基于 JVM 的编程语言,具备简洁、安全、高效的特性,已成为安卓开发的首选语言之一。通过网络请求拦截,Kotlin 可实现网址监控、访问时间记录等功能,满足公司上网监控需求。其简洁性有助于快速构建强大的监控应用,并便于后续维护与扩展。因此,Kotlin 在安卓上网监控应用开发中展现出广阔前景。
16 1
|
10天前
|
Android开发
Android开发显示头部Bar的需求解决方案--Android应用实战
Android开发显示头部Bar的需求解决方案--Android应用实战
13 0