Android httpservice и ajax - PullRequest
       24

Android httpservice и ajax

0 голосов
/ 27 марта 2012

У меня есть httpservice на устройстве Android:

/*some code*/
private static final String COMMAND_PATTERN = "/Commands/*";

...

registry.register(COMMAND_PATTERN, new ExecuteCommandHandler(context));

@Override
public void handle(HttpRequest request, HttpResponse response,
    HttpContext httpContext) throws HttpException, IOException {
    Log.e("", "INSIDE executor HANDLER");   
    String responseJSONString = "{\"result\":\"ok\"}";
    if (request instanceof HttpEntityEnclosingRequest) {
        responseJSONString="{\"result\":\"success!\"}";                                 
    }
    else responseJSONString="{\"result\":\"not instance of HttpEntityEnclosingRequest\"}";      

    final String jsonMessage = responseJSONString;
    HttpEntity entity = new EntityTemplate(new ContentProducer() {
        public void writeTo(final OutputStream outstream) throws IOException {
            Log.e("",jsonMessage);
            OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8");             
            writer.write(jsonMessage);
            writer.flush();
        }
    });

    response.setEntity(entity); 
}   

Я пытаюсь использовать ajax:

var ajx = $.getJSON('http://127.0.0.1:6789/Commands/');   
ajx.success(function(data){ 
    alert(data.result) 
}).error(function(data){ 
    alert('error') //IT HAPPENS EVERY TIME!!!
    alert(data.result) //EMPTY!!!
})

LogCat говорит:

03-26 23:24:53.447: ERROR/(4506): INSIDE executor HANDLER
03-26 23:24:53.487: ERROR/(4506): {"result":"not instance of HttpEntityEnclosingRequest"}

Но все в порядке! Проблема в том, что ajax всегда возвращает «ошибку»! Может быть, я что-то пропустил. Спасибо

1 Ответ

0 голосов
/ 29 декабря 2012

Чтобы получить JSON в javascript, вам нужно что-то вроде этого:

$.getJSON('http://127.0.0.1:6789/Commands/', function(data) {
    if(data && data.result) {
        //OK
        console.log(data.result);
    } else {
        //Data error
        console.log('Data error');
    }
}).error(function(data) {
    //Timeout or whatever
    console.log('Timeout or whatever');
    console.log(data);
}).complete(function(){
    //Always call this at the end of the request
    console.log('Completed');
});
...