【Android后台】客户端服务器之间的通信

本文章将针对AsyncHttpClient 的使用进行说明。

首先截图:

get - client

 

get - server

 

post - client

post - server

 

接下来看一下使用的文件吧,

server中有两个关键文件:

AndroidServerServlet.java

package com.ghj.packageofservlet;

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 AndroidServerServlet extends HttpServlet {

    private static final long serialVersionUID = 8294994660024495045L;

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/plain; charset=UTF-8");
        request.setCharacterEncoding("UTF-8");
        String clientData = request.getParameter("clientData");
        System.out.println(new String(clientData.getBytes("ISO8859-1"), "UTF-8"));
        PrintWriter out = response.getWriter();
        out.println("您好Android客户端,服务器端Get方法接收到您的请求!");
        out.flush();
        out.close();
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/plain; charset=UTF-8");
        request.setCharacterEncoding("UTF-8");
        System.out.println(request.getParameter("clientData"));
        PrintWriter out = response.getWriter();
        out.println("您好Android客户端,服务器端Post方法接收到您的请求!");
        out.flush();
        out.close();
    }
}

上面一个标准的servlet程序。

接下来是涉及配置的web.xml文件。

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

    <servlet>
        <servlet-name>AndroidServerServlet</servlet-name>
        <servlet-class>com.ghj.packageofservlet.AndroidServerServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>AndroidServerServlet</servlet-name>
        <url-pattern>/AndroidServerServlet</url-pattern>
    </servlet-mapping>
</web-app>

 

 

而在客户端程序中,只有两个文件以及一个库文件比较重要。

库文件是

android-async-http-1.4.6.jar

剩下一个布局文件和一个activity。

布局文件是一个点击触发事件的按钮:(作者还将这个按钮绝对居中了)

<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/sendGet"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="@string/sendGetBt" />

</RelativeLayout>

而在关键的activity中,

package com.ghj.packageofactivity;

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.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.app.Activity;

public class MainActivity extends Activity {
    
    private final String TAG = "MainActivity";
    private final String URL = "http://10.0.2.2:8080/AndroidServer/AndroidServerServlet";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button button = (Button)findViewById(R.id.sendGet);
        button.setOnClickListener(new OnClickListener(){
            @Override
            public void onClick(View view) {
//                sendGetRequest(view);
                sendPostRequest(view);
            }
        });
    }
    
    /**
     * 采用get方式向服务器端发送请求
     *
     * @author 高焕杰
     */
    void sendGetRequest(View view) {
        RequestParams params = new RequestParams();
        params.add("clientData", "您好服务器端的get方法!!!");
        params.setContentEncoding("UTF-8");
        new AsyncHttpClient().get(URL, params, new AsyncHttpResponseHandler(){
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                Log.i(TAG, statusCode + ":" + new String(responseBody));
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                Log.i(TAG, "请求失败!");
            }
        });
    }
    
    /**
     * 采用post方式向服务器端发送请求
     *
     * @author 高焕杰
     */
    void sendPostRequest(View view) {
        RequestParams params = new RequestParams();
        params.add("clientData", "您好服务器端的post方法!!!");
        new AsyncHttpClient().post(URL, params, new AsyncHttpResponseHandler(){
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                Log.i(TAG, statusCode + ":" + new String(responseBody));
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                Log.i(TAG, "请求失败!");
            }
        });
    }
}

 

 

例子比较小但是五脏俱全,我个人认为可以作为写类似代码的一个非常准确的参考。

附上源码的csdn的链接:

http://download.csdn.net/detail/wangshuxuncom/8116157

本博客是作为对作者的源码的一个解析与收录。

posted @ 2014-12-14 18:32  比企谷雪乃  阅读(364)  评论(0编辑  收藏  举报