English 中文(简体)
建立网上服务网的最佳途径
原标题:Best way to create a Web Service ON Android [closed]

我想就安文实施一个网络服务。 我想将我的装置作为server。 在对互联网进行一些研究后,我发现了一些选择:

  • SerDroid(星座小型网络服务器)

  • <>strong>i-Jetty (开放源网络集装箱,在安乐器平台上运行)

  • KWS(光重和快速网络服务器,特别为roid移动装置设计)

<><>>> 什么是最好的?

或者,我可以使用REST + JSON执行关于Andrea的网络服务。 我看不到REST + JSON......。

问题回答

REST+JSON服务

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;

        }

    }

}

用户使用的实例

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




相关问题
Android - ListView fling gesture triggers context menu

I m relatively new to Android development. I m developing an app with a ListView. I ve followed the info in #1338475 and have my app recognizing the fling gesture, but after the gesture is complete, ...

AsyncTask and error handling on Android

I m converting my code from using Handler to AsyncTask. The latter is great at what it does - asynchronous updates and handling of results in the main UI thread. What s unclear to me is how to handle ...

Android intent filter for a particular file extension?

I want to be able to download a file with a particular extension from the net, and have it passed to my application to deal with it, but I haven t been able to figure out the intent filter. The ...

Android & Web: What is the equivalent style for the web?

I am quite impressed by the workflow I follow when developing Android applications: Define a layout in an xml file and then write all the code in a code-behind style. Is there an equivalent style for ...

TiledLayer equivalent in Android [duplicate]

To draw landscapes, backgrounds with patterns etc, we used TiledLayer in J2ME. Is there an android counterpart for that. Does android provide an option to set such tiled patterns in the layout XML?

Using Repo with Msysgit

When following the Android Open Source Project instructions on installing repo for use with Git, after running the repo init command, I run into this error: /c/Users/Andrew Rabon/bin/repo: line ...

Android "single top" launch mode and onNewIntent method

I read in the Android documentation that by setting my Activity s launchMode property to singleTop OR by adding the FLAG_ACTIVITY_SINGLE_TOP flag to my Intent, that calling startActivity(intent) would ...

From Web Development to Android Development

I have pretty good skills in PHP , Mysql and Javascript for a junior developer. If I wanted to try my hand as Android Development do you think I might find it tough ? Also what new languages would I ...

热门标签