2010-07-12 3 views
4

Я хочу использовать веб-службу на Android. Я хочу использовать мое устройство как сервер. После выполнения некоторых исследований в Интернете, я нашел несколько вариантов:Лучший способ создания веб-сервиса на Android

  • SerDroid (маленький веб-сервер для Android платформы)

  • я-Jetty (с открытым исходным кодом веб-контейнер для запуска на Android мобильной платформы устройства)

  • KWS (легкий и быстрый веб-сервер, специально предназначенные для андроид мобильных устройств)

Что лучше?

В качестве альтернативы, я мог бы использовать REST + JSON для реализации веб-службы на Android? Я не undestand так много, что REST + JSON ...

+3

Может быть трудно. Если вы можете объяснить, какова ваша конечная цель, может быть совершенно другое решение, которое кто-то может вам дать? –

+0

Привет! Я хочу, чтобы один эмулятор мог вызвать службу, которая запускается на другом эмуляторе ... Служба может просто быть «Hello World». Меня особенно интересует такой тип общения. Спасибо – Deborah

+0

@Deborah, пожалуйста, добавьте свое разъяснение, отредактировав исходный вопрос, чтобы другие могли легко видеть информацию. –

ответ

0

Здесь examplse службы 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; 

     } 

    } 

} 

И пример использования для 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); 
+0

Ваш код не заполнен. – Ricardo

Смежные вопросы