安卓开发:客户端与服务器端交互(详细)

时间:2023-01-21 18:00:16

服务器端写一个简单的Servlet:

package login;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String name = request.getParameter("username");
        String pwd = request.getParameter("password");

        System.out.println("username~~" + new String(name.getBytes("iso-8859-1"), "utf-8"));

        System.out.println("password~~" + pwd);

        if ("abc".equals(name) && "123".equals(pwd)) {
            response.getOutputStream().write("登录成功".getBytes("utf-8"));

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

        }

    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        System.out.println("post方式提交数据");
        doGet(request, response);
    }

}

 

映射:

    <servlet-mapping>
        <servlet-name>LoginServlet</servlet-name>
        <url-pattern>/LoginServlet</url-pattern>
    </servlet-mapping>

    <welcome-file-list>
        <welcome-file>login.jsp</welcome-file>
    </welcome-file-list>

 

 

写好后启动Tomcat

 

安卓端

写两种方式:GET、POST:

布局:

 

<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/ev_username"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="请输入用户名" />

    <EditText
        android:id="@+id/ev_password"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="请输入密码" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="click1"
        android:text="get方式提交" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="click2"
        android:text="post方式提交" />

</LinearLayout>

 

获取提交:

最原始的方法:

package org.dreamtech.login;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {

    private EditText et_username;
    private EditText et_password;

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

        et_username = (EditText) findViewById(R.id.ev_username);
        et_password = (EditText) findViewById(R.id.ev_password);
    }

    // get
    public void click1(View v) {
        new Thread() {
            public void run() {
                try {
                    String name = et_username.getText().toString().trim();
                    String pwd = et_password.getText().toString().trim();

                    String path = "http://192.168.87.1:8080/Android_login/LoginServlet?username="
                            + URLEncoder.encode(name, "utf-8")
                            + "&password="
                            + URLEncoder.encode(pwd, "utf-8") + "";

                    URL url = new URL(path);
                    HttpURLConnection conn = (HttpURLConnection) url
                            .openConnection();
                    conn.setRequestMethod("GET");
                    conn.setConnectTimeout(5000);
                    int code = conn.getResponseCode();
                    if (code == 200) {
                        InputStream in = conn.getInputStream();
                        showToast(StreamTools.readStream(in));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            };
        }.start();

    }

    // post
    public void click2(View v) {
        new Thread() {
            public void run() {
                try {
                    String name = et_username.getText().toString().trim();
                    String pwd = et_password.getText().toString().trim();

                    String data = "username="
                            + URLEncoder.encode(name, "utf-8") + "&password="
                            + URLEncoder.encode(pwd, "utf-8") + "";

                    String path = "http://192.168.87.1:8080/Android_login/LoginServlet";

                    URL url = new URL(path);
                    HttpURLConnection conn = (HttpURLConnection) url
                            .openConnection();
                    conn.setRequestMethod("POST");

                    conn.setConnectTimeout(5000);

                    conn.setRequestProperty("Content-Type",
                            "application/x-www-form-urlencoded");
                    conn.setRequestProperty("Content-Length", data.length()
                            + "");

                    conn.setDoOutput(true);
                    conn.getOutputStream().write(data.getBytes());

                    int code = conn.getResponseCode();
                    if (code == 200) {
                        InputStream in = conn.getInputStream();
                        showToast(StreamTools.readStream(in));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            };
        }.start();
    }

    public void showToast(final String content) {
        runOnUiThread(new Runnable() {

            @Override
            public void run() {
                Toast.makeText(getApplicationContext(), content,
                        Toast.LENGTH_LONG).show();

            }
        });
    }
}

 

自定义读取流对象的工具类:

package org.dreamtech.login;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;

public class StreamTools {

    public static String readStream(InputStream in) throws Exception {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int len = -1;
        byte[] buffer = new byte[1024];
        while ((len = in.read(buffer)) != -1) {
            baos.write(buffer, 0, len);
        }
        in.close();
        String content = new String(baos.toByteArray(), "utf-8");
        return content;
    }

}

 

联网权限:

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

 

运行:

安卓开发:客户端与服务器端交互(详细)

 

成功!但是,我们发现这里的代码过多,有没有简单一些的方式呢?

有,httpclient

 

使用如下:

 

package org.dreamtech.login;

import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
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.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {

    private EditText et_username;
    private EditText et_password;

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

        et_username = (EditText) findViewById(R.id.ev_username);
        et_password = (EditText) findViewById(R.id.ev_password);
    }

    // get
    public void click1(View v) {
        new Thread() {
            public void run() {
                try {
                    String name = et_username.getText().toString().trim();
                    String pwd = et_password.getText().toString().trim();

                    String path = "http://192.168.87.1:8080/Android_login/LoginServlet?username="
                            + URLEncoder.encode(name, "utf-8")
                            + "&password="
                            + URLEncoder.encode(pwd, "utf-8") + "";

                    DefaultHttpClient client = new DefaultHttpClient();

                    HttpGet get = new HttpGet(path);

                    HttpResponse response = client.execute(get);

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

                    if (code == 200) {
                        InputStream in = response.getEntity().getContent();

                        showToast(StreamTools.readStream(in));
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    public void click2(View v) {

        new Thread() {
            public void run() {

                try {
                    String name = et_username.getText().toString().trim();
                    String pwd = et_password.getText().toString().trim();
                    String path = "http://192.168.87.1:8080/Android_login/LoginServlet";

                    DefaultHttpClient client = new DefaultHttpClient();

                    HttpPost post = new HttpPost(path);

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

                    BasicNameValuePair nameValuePair = new BasicNameValuePair(
                            "username", name);
                    BasicNameValuePair pwdValuePair = new BasicNameValuePair(
                            "password", pwd);
                    lists.add(nameValuePair);
                    lists.add(pwdValuePair);

                    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(
                            lists);

                    post.setEntity(entity);

                    HttpResponse response = client.execute(post);

                    int code = response.getStatusLine().getStatusCode();
                    if (code == 200) {
                        InputStream inputStream = response.getEntity()
                                .getContent();

                        showToast(StreamTools.readStream(inputStream));
                    }

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

            };
        }.start();

    }

    public void showToast(final String content) {
        runOnUiThread(new Runnable() {

            @Override
            public void run() {
                Toast.makeText(getApplicationContext(), content,
                        Toast.LENGTH_LONG).show();

            }
        });
    }
}

 

运行后成功!

 

这里还是感到代码复杂,有比这个还简单的吗?

还可以使用开源项目:

比如这里我使用AsyncHttpClient

这个开源项目有很多强大的功能,这里只使用基本的GET和POST请求

package org.dreamtech.login;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import org.apache.http.Header;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {

    private EditText et_username;
    private EditText et_password;
    private String path;

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

        et_username = (EditText) findViewById(R.id.ev_username);
        et_password = (EditText) findViewById(R.id.ev_password);
    }

    // get
    public void click1(View v) {
        try {
            String name = et_username.getText().toString().trim();
            String pwd = et_password.getText().toString().trim();

            path = "http://192.168.87.1:8080/Android_login/LoginServlet?username="
                    + URLEncoder.encode(name, "utf-8")
                    + "&password="
                    + URLEncoder.encode(pwd, "utf-8") + "";

            AsyncHttpClient client = new AsyncHttpClient();
            client.get(path, new AsyncHttpResponseHandler() {

                @Override
                public void onSuccess(int statusCode, Header[] headers,
                        byte[] responseBody) {
                    try {
                        Toast.makeText(getApplicationContext(),
                                new String(responseBody, "utf-8"),
                                Toast.LENGTH_LONG).show();
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }

                }

                @Override
                public void onFailure(int statusCode, Header[] headers,
                        byte[] responseBody, Throwable error) {
                    Toast.makeText(getApplicationContext(), "错误",
                            Toast.LENGTH_LONG).show();

                }
            });

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

    public void click2(View v) {
        String name = et_username.getText().toString().trim();
        String pwd = et_password.getText().toString().trim();
        String path = "http://192.168.87.1:8080/Android_login/LoginServlet";
        AsyncHttpClient client = new AsyncHttpClient();

        RequestParams params = new RequestParams();
        params.put("username", name);
        params.put("password", pwd);

        client.post(path, params, new AsyncHttpResponseHandler() {

            @Override
            public void onSuccess(int statusCode, Header[] headers,
                    byte[] responseBody) {

                try {
                    Toast.makeText(getApplicationContext(),
                            new String(responseBody, "utf-8"),
                            Toast.LENGTH_LONG).show();
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers,
                    byte[] responseBody, Throwable error) {
                Toast.makeText(getApplicationContext(), "错误", Toast.LENGTH_LONG)
                        .show();
            }
        });

    }

}