开发者

Best way to create a Web Service ON Android [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance. Closed 9 years ago.

I want to implement a Web Service on Android.. I want to use my device as server. After doing some research on the internet, I found several options:

  • SerDroid (small web server for the Android platform)

  • i-Jetty (open-source web container to run on the Android mobile device platform)

  • KWS (lightweight and fast web server especially designed for android mobile devices)

Wh开发者_如何学运维at is the best?

Alternatively, I could use REST + JSON to implement Web Service on Android? I don't undestand so much what is REST + JSON...


Here examplse of REST+JSON service

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;

        }

    }

}

And example of use for 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);
    }

}

And call from source:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜