- 浏览: 311525 次
- 性别:
- 来自: 成都
文章分类
最新评论
-
a455642158:
xiajy 写道他妈的都该名字了,更可恶的金山手机助手是:sj ...
解决ADB server didn't ACK问题 -
wwt455653509:
关闭tadb.exe,重启eclipse搞定
解决ADB server didn't ACK问题 -
Frederic:
感谢,真是帮了大忙!腾讯
解决ADB server didn't ACK问题 -
xiajy:
他妈的都该名字了,更可恶的金山手机助手是:sjk_daemon ...
解决ADB server didn't ACK问题 -
xiaofeilv321:
赞同
解决ADB server didn't ACK问题
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
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
发表评论
-
RSS
2011-05-05 10:18 0RSS手机阅读 -
checkout lwuit源代码
2010-12-07 16:22 1211步骤一:安装SVN 步骤二:去 LWUIT 官网免费注册一个 ... -
wave混音的实现(2)
2010-11-11 20:43 2372关于混音算法,参考的是http://jacky-zhang.i ... -
混音算法
2010-11-11 20:41 4957一、最简单的混音算法 现在一般的软件混音算法是对输入的音频数据 ... -
wave混音的实现(1)
2010-11-11 20:36 2186先看关于wav文件的头信息 下面是封装好的一个辅助类。用于生 ... -
直接通过链接打开模拟器
2010-03-30 22:13 1050提示:需要JDK1.5 或以上支持 在jad的url之前添加 ... -
j2me优化秘密
2008-04-25 13:36 1715以下是经验总结: *只优化需要的代码 *只在有价值的地方优化 ... -
j2me图片任意角度翻转算法
2008-04-24 13:56 1249import javax.microedition.lcdui ... -
OpenBaseMovil
2008-04-17 11:05 1490http://www.openbasemovil.org/do ... -
Forum_Nokia_Technical_Library_v1_30_en(chm)
2008-04-16 16:13 1119Forum Nokia Technical Library ... -
mwt
2008-04-10 13:16 1419自己写了一个demo及一些练习 -
Different platform, different keycodes
2008-04-03 09:55 1518package opusmicro.keycode.tes ... -
floggy
2008-03-27 14:31 1308As J2ME developers we couldn't ... -
Canvas翻页效果
2008-03-26 16:01 2648仅供交流学习 -
Canvas下调用输入法
2008-03-26 15:45 2375示例程序。 -
J2ME中文的支持问题
2008-03-11 14:41 1474在使用MotoJ2SDK进行J2ME应用程序的开发,经常会遇到 ... -
camera support
2008-03-11 12:48 1471microedition.platform 平台名称,如j ... -
keycodes on different devices
2008-03-11 11:50 1151Device UP DOWN LEFT RIG ... -
各品牌手机键值
2008-03-11 11:48 2298原文(http://www.jum.cn/bbs/archiv ... -
A J2ME FAQ
2008-03-11 11:41 1780J2ME technologies What are the ...
相关推荐
A little bert
little eye mobile amp
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 ...
A Little Book of R For Time Series R语言时间序列分析教程PDF
It sounds like you need a little (or maybe a lot of) Ajax in your life. Asynchronous programming lets you turn your own web sites into smooth, slick, responsive applications that make your users feel...
The_Little_SAS_Book__A_Primer__Fourth_Edition
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 book of r for time series a little book of r for time series 时间序列 R语言
This is a kind of proactive and interactive reading experience that you probably aren't familiar with yet, so log on to http:/ / en. wikibooks. org and take a look around at all the possibilities....
Mobile devices outnumber desktop and laptop computers three to one worldwide, yet little information is available for designing and ... * Learn how to justify a mobile product by building it on a budget
a little book of R for biomedical statistics
ASP.NET MVC has always been a good platform on which to implement REST, but with the advent of the Web API it has now become even better. This book will show you why it's great and how to get the ...
The Little Book on CoffeeScript 中文+英文版
Lesson 24 A little monkey练习题及答案.doc
Along the way, you'll learn about Corona's API functions and build three common kinds of mobile games from scratch that can run on the iPhone, iPad, Kindle Fire, Nook Color, and all other Android ...
初学简笔a little