在Android上创建Web服务的最佳方式

时间:2010-07-12 10:37:19

标签: android web-services web-applications android-emulator

我想在Android上实施网络服务..我想将我的设备用作 服务器 。在互联网上做了一些研究之后,我找到了几个选择:

  • SerDroid (适用于Android平台的小型网络服务器)

  • i-Jetty (在Android移动设备平台上运行的开源网络容器)

  • KWS (专为Android移动设备设计的轻量级快速网络服务器)

什么是最好的?

或者,我可以使用 REST + JSON 在Android上实现Web服务?我不是很清楚什么是REST + JSON ...

1 个答案:

答案 0 :(得分:0)

package rainprod.utils.internetservice;

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.json.JSONObject;

import android.os.Handler;
import android.os.Message;

public abstract class InternetService extends Handler {

    public static final int CONNECTING = 1;
    public static final int UPLOADING = 2;
    public static final int DOWNLOADING = 3;
    public static final int COMPLETE = 4;
    public static final int ERROR = -1;


    private IInternetService listener;

    public InternetService(IInternetService listener) {
        this.listener = listener;
    }

    public DefaultHttpClient getDefaultClient() {
        HttpParams httpParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParams, 15000);
        HttpConnectionParams.setSoTimeout(httpParams, 15000);
        DefaultHttpClient httpClient = new DefaultHttpClient(httpParams);
        return httpClient;
    }

    public void postJson(JSONObject postObject, String functionName, int responseCode,
            int subResponseCode, boolean isThreadly) {
        DefaultHttpClient httpClient = this.getDefaultClient();
        HttpPost postRequest = new HttpPost(this.getServiceURLString() + functionName);

        this.restApiPostRequest(httpClient, postRequest, postObject,
                responseCode, subResponseCode);
    }

    abstract public String getServiceURLString();



    public void restApiPostRequest(final DefaultHttpClient httpclient,
            final HttpPost request, final JSONObject postObject,
            final int responseCode, final int subResponseCode) {
        new Thread(new Runnable() {

            @Override
            public void run() {

                try {
                    try {
                        StringEntity se = new StringEntity(postObject
                                .toString(), HTTP.UTF_8);
                        se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE,
                                "application/json"));
                        request.setEntity(se);
                        HttpResponse response = httpclient.execute(request);
                        HttpEntity entity = response.getEntity();
                        if (entity != null) {
                            ByteArrayOutputStream baos = new ByteArrayOutputStream();
                            DataInputStream dis = new DataInputStream(entity
                                    .getContent());
                            byte[] buffer = new byte[1024];// In bytes
                            int realyReaded;
                            double contentSize = entity.getContentLength();
                            double readed = 0L;
                            while ((realyReaded = dis.read(buffer)) > -1) {
                                baos.write(buffer, 0, realyReaded);
                                readed += realyReaded;
                                sendProgressMessage((double) contentSize,
                                        readed, responseCode, DOWNLOADING);
                            }
                            sendCompleteMessage(new InternetServiceResponse(
                                    responseCode, baos, subResponseCode),
                                    COMPLETE);
                        } else {

                            sendErrorMessage(responseCode,
                                    new Exception("Null"), request.getURI()
                                            .toString(), ERROR);

                        }
                    } catch (ClientProtocolException e) {
                        sendErrorMessage(responseCode, e, request.getURI()
                                .toString(), ERROR);
                    } catch (IOException e) {
                        sendErrorMessage(responseCode, e, request.getURI()
                                .toString(), ERROR);
                    } catch (OutOfMemoryError e) {
                        sendErrorMessage(responseCode, new Exception(
                                "Out memory"), request.getURI().toString(),
                                ERROR);
                    } finally {
                        httpclient.getConnectionManager().shutdown();
                    }
                } catch (NullPointerException e) {
                    sendErrorMessage(responseCode, e, request.getURI()
                            .toString(), ERROR);

                }

            }
        }).start();

    }

    private void sendProgressMessage(double contentSize, double readed,
            int responseCode, int progressCode) {
        this.sendMessage(this.obtainMessage(progressCode,
                new InternetServiceResponse(contentSize, readed, responseCode)));

    }

    protected void sendErrorMessage(int responseCode, Exception exception,
            String string, int errorCode) {
        this.sendMessage(this.obtainMessage(
                errorCode,
                new InternetServiceResponse(responseCode, exception
                        .getMessage())));
    }

    protected void sendCompleteMessage(InternetServiceResponse serviceResponse,
            int completeCode) {
        this.sendMessage(this.obtainMessage(completeCode, serviceResponse));
    }

    @Override
    public void handleMessage(Message msg) {
        final InternetServiceResponse bankiServiceResponse = (InternetServiceResponse) msg.obj;
        switch (msg.what) {
        case UPLOADING:

            break;

        case DOWNLOADING:
            this.listener.downloadingData(bankiServiceResponse.contentSize,
                    bankiServiceResponse.readed,
                    bankiServiceResponse.responseCode);
            break;
        case COMPLETE:
            this.listener.completeDownload(bankiServiceResponse);
            break;
        case ERROR:
            this.listener.errorHappen(bankiServiceResponse.textData,
                    bankiServiceResponse.responseCode);
            break;

        }

    }

}

用于UserAPI的示例

package ru.orionsource.missingcar.api;

import rainprod.utils.internetservice.IInternetService;
import rainprod.utils.internetservice.InternetService;
import ru.orionsource.missingcar.classes.User;

public class UserAPI extends InternetService {

    public UserAPI(IInternetService listener) {
        super(listener);
    }

    @Override
    public String getServiceURLString() {
        return "http://ugnali.orionsource.ru/u_api/?apiuser.";
    }

    public void userLogin(User user) {
        this.postJson(user.toJson(), "logonUser", 1, 0, true);
    }

}

来自消息来源:

this.userAPI = new UserAPI(this);
User selected = new User();
selected.email = this.accounts.get(arg2).name;
this.userAPI.userLogin(selected);