`
jacky-zhang
  • 浏览: 316730 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类
最新评论

a little experience on mobile ajax api

    博客分类:
  • j2me
阅读更多
mobile ajax api ¶

Table of Contents

   1. Introduction
   2. How to invoke request
         1. 1) asynchronism mode
         2. 2) synchronism mode
   3. How to arouse event
   4. How to invoke response
         1. 1) asynchronism mode
         2. 2) synchronism mode
   5. Summarize the issues
         1. How to do http authentication
         2. How to send request with post method
               1. 1) Send simple message
               2. 2) Upload file data(use multipartBoundary)
                     1. (1) General
                     2. (2) Special for Flickr API
         3.
         3. If we can set http header attribute when send request
         4. How to get header attribute from response
         5. How to download file/image
               1. 1) Send parameters to obtain file list
               2. 2) Parse the response from server
               3. 3) Obtain each file's property
               4. 4) Send url to download file
         6. The usages, relathionships of main classes and interfaces in asyncrhonous …
               1. 1) Aid class usages
               2. 2) Interface usages
               3. 3) Main class usages
         7. The usages of all PUBLIC API/interface and related arguments in …
               1. 1) Result class, ResultException? class
               2. 2) Other classes
         8. Progress listeners
         9. See Also

Introduction ¶

Mobile Ajax API are made of 4 parts:a streaming Atom API, A JASON parser API, An Expression Language API and Asynchronous I/O API, the core are A JASON parser API, An Expression Language API and Asynchronous I/O API.The very important core is asynchronous I/O.And Expression Languange is used for invoke JASON parser to parse the data from server and obtain the result;Asynchronous I/O is very important,it offers these functions:

    * Asynchronous versions of HTTP Get and Post
    * HTTP Basic Authentication
    * Multipart MIME (sender only)
    * Progress listeners

How to invoke request ¶

It's very simple for user to invoke Mobile Ajax API, just like below
1) asynchronism mode ¶

private void doGetFriends(){
    ...
    Request.get(
        final String url,         //http address
        final Arg[] inputArgs,    //parameters behind url
        final Arg[] httpArgs,     //HTTP headers
        final RequestListener listener,    //event listener, monitor progress listener and response listener
        final Object context);             //the UI display
      } 

or

private void doPostFriends(){
    ...
    Request.post(
        final String url,        //http address,for example "http://twitter.com/statuses/friends.json"
        final Arg[] inputArgs,   //parameters behind url
        final Arg[] httpArgs,    //HTTP headers
        final RequestListener listener,  //event listener, monitor progress listener and response listener
        final PostData multiPart,        //HTTP POST method post data
        final Object context);           //the UI display
}

2) synchronism mode ¶

private void doGetFriends(){
    ...
    Response response = Response.get(
        final String url,        //http address
        final Arg[] inputArgs,   //parameters behind url
        final Arg[] httpArgs,    //HTTP headers
        final RequestListener listener);   //event listener, monitor progress listener and response listener
    ...
}

or

private void doPostFriends(){
    ...
    Response response = Response.post(
        final String url,          //http address
        final Arg[] inputArgs,     //parameters behind url
        final Arg[] httpArgs,      //HTTP headers
        final RequestListener listener,  //event listener, monitor progress listener and response listener
        final PostData multiPart)        //HTTP POST method post data
    ...
}

How to arouse event ¶

Arouse event by implements CommandAction? interface, when click button, commandAction'll invoke accordingly method, for example

public void commandAction(Command c, Displayable d){
    ...
    if(c == getFriendsCommand){
        doGetFriends();
    }
}

How to invoke response ¶
1) asynchronism mode ¶

Need implements the method of RequestListener?,below is one of method we implement.

public void done(final Object context, final Response response) throws Exception {
     ...
     handleGetFriendsResponse(response);   //parse data from server
}

2) synchronism mode ¶

private void doGetFriends(){
    ...
    Response response = Response.get(
        final String url,        //http address
        final Arg[] inputArgs,   //parameters behind url
        final Arg[] httpArgs,    //HTTP headers
        final RequestListener listener);   //event listener, monitor progress listener and response listener
    handleGetFriendsResponse(response);   //parse data from server
}

Summarize the issues ¶
How to do http authentication ¶

        private Arg[] getHttpArgs(String tag){
String credentials = "Basic " + BasicAuth.encode(user, password);
Arg authArg = new Arg(Arg.AUTHORIZATION, credentials);
Arg[] argTag = {authArg};
return tag==null?argTag:null;
}
Request.get(url, null, getHttpArgs(null), this, context);

How to send request with post method ¶
1) Send simple message ¶

                Arg[] args = {new Arg("source", "twister")};
Request.post(url, args, getHttpArgs(null), this, null, context);

2) Upload file data(use multipartBoundary) ¶
(1) General ¶

                byte[] photoBits = ...    //obtain the file data
                final Arg apiKeyArg = new Arg("api_key", API_KEY);
                final Arg photoArg = new Arg("photo", "img" + Long.toString(System.currentTimeMillis(), 16) + ".jpg");
final Arg[] apiKeyArgs = {new Arg(Arg.CONTENT_DISPOSITION, "form-data; name=" + apiKeyArg.getKey())};
                final Arg[] photoArgs = {
                    new Arg(Arg.CONTENT_TYPE, "image/jpeg"),
                    new Arg(Arg.CONTENT_DISPOSITION, "form-data; name=" + photoArg.getKey() + "; filename=" + photoArg.getValue())
                };
final String multipartBoundary = Long.toString(System.currentTimeMillis(), 16) + "--" + getClass().getName();
final Arg[] httpArgs = {
new Arg("MIME-Version", "1.0"),
new Arg("Content-Type", "multipart/form-data; boundary=" + multipartBoundary)
};
final Part[] postData = {
new Part(apiKeyArg.getValue().getBytes(), apiKeyArgs),
new Part(photoBits, photoArgs)};
final PostData mp = new PostData(postData, multipartBoundary);
Request.post(url, null, httpArgs, this, mp, context);

(2) Special for Flickr API ¶

    Add a new Arg to httpArgs, that is apiSigArg, it role is security.At client side, the sign() method dealed with it's value; at server side also do the same thing like sign() method, and then compare them, if different, server'll refuse request; if the same, accept request.

                    byte[] photoBits = ...    //obtain the file data
                    final Arg apiKeyArg = new Arg("api_key", API_KEY);
                    final Arg photoArg = new Arg("photo", "img" + Long.toString(System.currentTimeMillis(), 16) + ".jpg");
    final Arg apiSigArg = new Arg("api_sig", null);
    final Arg[] postArgs = { apiKeyArg, photoArg, apiSigArg};
    final Arg[] apiKeyArgs = {new Arg(Arg.CONTENT_DISPOSITION, "form-data; name=" + apiKeyArg.getKey())};
                    final Arg[] photoArgs = {
                        new Arg(Arg.CONTENT_TYPE, "image/jpeg"),
                        new Arg(Arg.CONTENT_DISPOSITION, "form-data; name=" + photoArg.getKey() + "; filename=" + photoArg.getValue())
                    };
    final String multipartBoundary = Long.toString(System.currentTimeMillis(), 16) + "--" + getClass().getName();
    final Arg[] httpArgs = {
    new Arg("MIME-Version", "1.0"),
    new Arg("Content-Type", "multipart/form-data; boundary=" + multipartBoundary)
    };
    Arg signedArg = sign(postArgs);  //obtain apiSigArg
    final Arg[] apiSigArgs = {new Arg(Arg.CONTENT_DISPOSITION, "form-data; name=" + signedArg.getKey())};
    final Part[] postData = {
    new Part(apiKeyArg.getValue().getBytes(), apiKeyArgs),
                            new Part(photoBits, photoArgs)},
    new Part(signedArg.getValue().getBytes(), apiSigArgs)};
    final PostData mp = new PostData(postData, multipartBoundary);
    Request.post(url, null, httpArgs, this, mp, context);

    Sign() method used for combine all the httpArgs's keys and values,except apiSigArg and postData, then MD5 encryption

    private static Arg sign(final Arg[] args) throws Exception {
            if (args == null) {
                throw new IllegalArgumentException("args cannot be null");
            }
            if (args.length == 0) {
                throw new IllegalArgumentException("args must not be empty");
            }
            final StringBuffer concat = new StringBuffer();
            // first append the shared secret
            concat.append(SHARED_SECRET);
            // now append the args, which are assumed to be sorted by key
            for (int i=0; i < args.length; i++) {
                if (args[i] != null) {
                    // do not include the signature or the photo arg in the signature computation
                    final String key = args[i].getKey();
                    if ("api_sig".equals(key) || "photo".equals(key)) {
                        continue;
                    }
                    if (key != null) {
                        concat.append(key);
                    }
                    final String value = args[i].getValue();
                    if (value != null) {
                        concat.append(value);
                    }
                }
            }
            final byte[] input = concat.toString().getBytes();
            // an md5 hash is 128 bits = 16 bytes
            final byte[] hash = new byte[16];
            final java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
            md.update(input, 0, input.length);
            md.digest(hash, 0, hash.length);
            final StringBuffer sig = new StringBuffer(hash.length);
            for (int i=0; i < hash.length; i++) {
                sig.append(Integer.toHexString((hash[i] & 0xf0) >>> 4));
                sig.append(Integer.toHexString((hash[i] & 0x0f)));
            }
            // the sig arg, whose value should be null (a placeholder), is replaced with the sig
            int sigIndex = -1;
            for (int i=0; i < args.length; i++) {
                if ("api_sig".equals(args[i].getKey())) {
                    if (args[i].getValue() != null) {
                        throw new IllegalArgumentException("the api_sig arg must be null to replace with the actual signature");
                    }
                    sigIndex = i;
                }
            }
            if (sigIndex < 0) {
                throw new IllegalArgumentException("the api_sig arg must be present");
            }
            return args[sigIndex] = new Arg("api_sig", sig.toString());
        }

If we can set http header attribute when send request ¶

       final Arg[] httpArgs = {
new Arg("MIME-Version", "1.0"),
new Arg("Content-Type", "multipart/form-data; boundary=" + multipartBoundary)
};
Request.post(url, null, httpArgs, this, mp, context);

How to get header attribute from response ¶

        Arg[] headers = response.getHeaders();

How to download file/image ¶
1) Send parameters to obtain file list ¶

                Arg[] args = {
new Arg("api_key", API_KEY),
new Arg("format", "json"),
...
};
Request.get(url, args, null, this, context);

2) Parse the response from server ¶

                Result result = response.getResult();
Photo[] photos = new Photo[result.getSizeOfArray("photos.photo")];  //inner class, saved data
for (int i=0; i < photos.length; i++) {
Photo foto = new Photo();
String root = "photos.photo[" + i + "].";
foto.id = result.getAsString(root + "id");
foto.owner = result.getAsString(root + "owner");
...
photos[i] = foto;
}

3) Obtain each file's property ¶

        for (int i=0; i < photos.length; i++) {
final Photo foto = photos[i];
final Image thumb = getImage(foto, "t");
}
Image getImage(Foto foto,String size){
String imageLoc = "http://farm" + foto.farm + ".static.flickr.com/" +...;
return loadImage(imageLoc);
}

4) Send url to download file ¶

    private Image loadImage(String location){
                HttpConnection conn = null;
InputStream is = null;
conn = (HttpConnection) Connector.open(location);
                conn.setRequestProperty("accept", "image/*");
final int responseCode = conn.getResponseCode();
if (responseCode != HttpConnection.HTTP_OK) {
// TODO: handle redirects
return null;
}
int totalToReceive = conn.getHeaderFieldInt(Arg.CONTENT_LENGTH, 0);
is = new ProgressInputStream(conn.openInputStream(), totalToReceive, this, null, 1024);
ByteArrayOutputStream bos = new ByteArrayOutputStream(Math.max(totalToReceive, 8192));
byte[] buffer = new byte[4096];
for (int nread = is.read(buffer); nread >= 0; nread = is.read(buffer)) {
bos.write(buffer, 0, nread);
}
return Image.createImage(new ByteArrayInputStream(bos.toByteArray()));
}

The usages, relathionships of main classes and interfaces in asyncrhonous I/O ¶
1) Aid class usages ¶

    BasicAuth? class see How to do http authentication

    Arg, Part, PostData? class see How to send request with post method

    ProgressInputStream? class see Send url to download file

    Response class see Parse the response from server

2) Interface usages ¶

    RequestListener? interface extends ProgressListener? interface and user implements RequestListener?

    include readProgress() method, writeProgress() method, done() method, for example

        public void done(final Object context, final Response response) throws Exception {
...
if(context==home){  //the UI displayed
handleGetFriendsResponse(response);   //parse data from server
}
}

3) Main class usages ¶

    Request class see

    *How to do http authentication
    *How to send request with post method
    *If we can set http header attribute when send request
    *How to get header attribute from response

The usages of all PUBLIC API/interface and related arguments in asynchronous I/O ¶
1) Result class, ResultException? class ¶

                Result result = response.getResult();
try {
Photo[] photos = new Photo[result.getSizeOfArray("photos.photo")];  //inner class, save data
int maxPage = Integer.valueOf(result.getAsString("photos.pages")).intValue();
for (int i=0; i < photos.length; i++) {
Photo foto = new Photo();
String root = "photos.photo[" + i + "].";
foto.id = result.getAsString(root + "id");
foto.owner = result.getAsString(root + "owner");
...
photos[i] = foto;
}
for (int i=0; i < photos.length; i++) {
Photo foto = photos[i];
status.setText("Loading " + foto.id);
...
}
} catch (ResultException jex) {
return;
}

2) Other classes ¶

*The usages, relathionships of main classes and interfaces in asyncrhonous I/O
Progress listeners ¶

    Implements ProgressListener? and handle logic at implemented methods

        public void readProgress(final Object context, final int bytes, final int total) {
status.setText(total > 0 ? (((bytes * 100) / total) + "%") : Integer.toString(bytes));  //a StringItem display percentage
}
public void writeProgress(final Object context, final int bytes, final int total) {
status("Uploading... " + (total > 0 ? (((bytes * 100) / total) + "%") : Integer.toString(bytes)));  //a StringItem display percentage
}

See Also ¶

NONE
分享到:
评论

相关推荐

    A little bert.7z

    标题"A little bert.7z"和描述"A little bert"似乎涉及到一个与BERT相关的主题,BERT全称为Bidirectional Encoder Representations from Transformers,是Google在2018年推出的一种预训练语言模型,它在自然语言处理...

    A Little Java A Few Patterns

    A Little Java A Few Patterns 不错的书

    A Little Java, A Few Patterns

    Java is a new object-oriented programming language that was developed by Sun Microsystems for programming the Internet and intelligent appliances. In a very short time it has become one of the most ...

    littlefs_littlefs_

    2. **挂载文件系统:** 然后,通过littleFS的API将SPI闪存挂载为文件系统,这个过程会创建必要的文件系统结构。 3. **文件操作:** 之后,就可以使用标准的文件操作函数(如fopen、fwrite、fread等)进行文件的读写和...

    mobile apm little eye

    ### Mobile APM Little Eye:深度解析与操作指南 #### 一、Little Eye 概述 Little Eye 是一款专为移动应用性能管理(APM)设计的工具,它可以帮助开发者深入了解移动应用在各种设备上的运行状况,包括但不限于...

    A Little Bit Wicked.pdf

    Based on the given excerpt from "A Little Bit Wicked," this analysis will focus on extracting relevant IT knowledge points. However, it's important to note that the provided content is a historical ...

    A Little Book of Python for Multivariate Analysis 等 28 本

    A Little Book of Python for Multivariate Analysis.epub Algorithmic Information Theory - Review For Physicists And Natural Scientists.pdf Artificial Inteligence - Leonardo Araujo dos Santos.epub ...

    a little sas 最新版

    《a little sas 最新版》实际上指的是《The Little SAS Book: A Primer, Fourth Edition》,这是一本深入浅出地介绍SAS编程语言的书籍,非常适合初学者入门。本书作者Lora D. Delwiche和Susan J. Slaughter都是在SAS...

    a-little-java-a-few-patterns_书签精校版

    《A Little Java, A Few Patterns》是一本关于Java编程语言以及设计模式的书籍,作者为Matthias Felleisen和Daniel P. Friedman,这本书籍受到了豆瓣8.2高分的评价,被认为是学习Java语言和设计模式方面的优秀教程。...

    A Little Book of R For Time Series

    《R语言时间序列分析教程》是Avril Coghlan撰写的,旨在向读者介绍如何利用R语言进行时间序列的分析。R语言是一种广泛使用的免费统计软件(官方网站***),它不仅允许用户以交互模式进行数据分析,还支持进行简单的...

    a little book of r for time series

    本书名为《a little book of r for time series》,由Avril Coghlan编写,是一本关于使用R语言进行时间序列分析的入门书籍。R语言是一种广泛应用于统计计算和图形表示的编程语言。这本书致力于向读者介绍如何使用R...

    esp_littlefs:用于ESP-IDF的LittleFS端口.zip

    5. **使用标准API**:LittleFS提供了与标准POSIX API兼容的接口,如`open()`, `read()`, `write()`, `close()`等,使得开发者可以方便地进行文件操作。 通过这个压缩包,开发者可以获取ESP-IDF对LittleFS的完整支持...

    A Little of .NET-.NET Architecture

    哎,我的自私。本来想修改一下再上传,但实在是没有时间了,请见谅,罪过,罪过。

    LittlevGL_v6.0.pdf

    这个是littleVGL图形开源库的帮助文档,其中包括littleVGL的介绍,littleVGL的移植和API的使用; 这个是littleVGL图形开源库的帮助文档,其中包括littleVGL的介绍,littleVGL的移植和API的使用; 这个是littleVGL...

    Lesson 24 A little monkey练习题及答案.doc

    这篇文档是针对英语学习的一份练习材料,主题是"Lesson 24 A Little Monkey",包含了一些基础的英语对话和词汇配对练习。这个练习旨在帮助学习者掌握日常生活中的简单交流用语,特别是与食物和水果相关的表达。 一...

Global site tag (gtag.js) - Google Analytics