├── android
├── README.md
├── LICENSE
├── lib
│ ├── okio-1.2.0.jar
│ ├── okhttp-2.2.0.jar
│ └── README
├── dist
│ ├── com.atticoos.tiokhttp-android-1.0.0.zip
│ ├── com.atticoos.tiokhttp-android-1.1.0.zip
│ └── com.atticoos.tiokhttp-android-1.1.1.zip
├── .settings
│ ├── org.eclipse.jdt.core.prefs
│ └── org.eclipse.jdt.apt.core.prefs
├── src
│ └── com
│ │ └── atticoos
│ │ └── tiokhttp
│ │ ├── InvalidMethodException.java
│ │ ├── TitaniumOkhttpModule.java
│ │ ├── HttpClientProxy.java
│ │ ├── OkHttpClientProxy.java
│ │ ├── HttpClient.java
│ │ └── ProxyRequest.java
├── build.properties
├── Makefile
├── assets
│ └── README
├── timodule.xml
├── platform
│ └── README
├── manifest
├── .project
├── .classpath
├── example
│ └── app.js
├── build.xml
└── documentation
│ └── index.md
├── LICENSE
├── .gitignore
├── assets
└── README
├── documentation
└── index.md
├── example
└── app.js
└── README.md
/android/README.md:
--------------------------------------------------------------------------------
1 | ../README.md
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | TODO: place your license here and we'll include it in the module distribution
2 |
--------------------------------------------------------------------------------
/android/LICENSE:
--------------------------------------------------------------------------------
1 | TODO: place your license here and we'll include it in the module distribution
2 |
--------------------------------------------------------------------------------
/android/lib/okio-1.2.0.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/atticoos/titanium-okhttp/HEAD/android/lib/okio-1.2.0.jar
--------------------------------------------------------------------------------
/android/lib/okhttp-2.2.0.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/atticoos/titanium-okhttp/HEAD/android/lib/okhttp-2.2.0.jar
--------------------------------------------------------------------------------
/android/lib/README:
--------------------------------------------------------------------------------
1 | You can place any .jar dependencies in this directory and they will be included
2 | when your module is being compiled.
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | android/.apt_generated
2 | build/
3 | android/android/build
4 | android/build
5 | android/dist/*.jar
6 | android/libs
7 | android/bin
8 |
--------------------------------------------------------------------------------
/android/dist/com.atticoos.tiokhttp-android-1.0.0.zip:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/atticoos/titanium-okhttp/HEAD/android/dist/com.atticoos.tiokhttp-android-1.0.0.zip
--------------------------------------------------------------------------------
/android/dist/com.atticoos.tiokhttp-android-1.1.0.zip:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/atticoos/titanium-okhttp/HEAD/android/dist/com.atticoos.tiokhttp-android-1.1.0.zip
--------------------------------------------------------------------------------
/android/dist/com.atticoos.tiokhttp-android-1.1.1.zip:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/atticoos/titanium-okhttp/HEAD/android/dist/com.atticoos.tiokhttp-android-1.1.1.zip
--------------------------------------------------------------------------------
/android/.settings/org.eclipse.jdt.core.prefs:
--------------------------------------------------------------------------------
1 | #Thu Sep 02 15:18:34 CDT 2010
2 | eclipse.preferences.version=1
3 | org.eclipse.jdt.core.compiler.processAnnotations=enabled
4 |
--------------------------------------------------------------------------------
/android/src/com/atticoos/tiokhttp/InvalidMethodException.java:
--------------------------------------------------------------------------------
1 | package com.atticoos.tiokhttp;
2 |
3 | class InvalidMethodException extends Exception
4 | {
5 | public InvalidMethodException (String method) {
6 | super("Invalid HTTP request method: " + method);
7 | }
8 | }
--------------------------------------------------------------------------------
/android/build.properties:
--------------------------------------------------------------------------------
1 | titanium.platform=/Users/ajwhite/Library/Application Support/Titanium/mobilesdk/osx/3.4.0.GA/android
2 | android.platform=/Users/ajwhite/Development/android-sdk-macosx/platforms/android-17
3 | google.apis=/Users/ajwhite/Development/android-sdk-macosx/add-ons/addon-google_apis-google-17
4 |
--------------------------------------------------------------------------------
/android/.settings/org.eclipse.jdt.apt.core.prefs:
--------------------------------------------------------------------------------
1 | #Thu Sep 02 15:18:34 CDT 2010
2 | eclipse.preferences.version=1
3 | org.eclipse.jdt.apt.aptEnabled=true
4 | org.eclipse.jdt.apt.genSrcDir=.apt_generated
5 | org.eclipse.jdt.apt.reconcileEnabled=true
6 |
7 | org.eclipse.jdt.apt.processorOptions/kroll.jsonFile=titanium-okhttp.json
8 |
--------------------------------------------------------------------------------
/android/Makefile:
--------------------------------------------------------------------------------
1 | MODULE_PATH = ~/Library/Application\ Support/Titanium
2 | MODULE_ZIP = tiokhttp.zip
3 |
4 | all:
5 | ant
6 | cp dist/com.atticoos.tiokhttp-android-1.1.1.zip $(MODULE_PATH)/$(MODULE_ZIP)
7 | cd $(MODULE_PATH) && \
8 | unzip -o $(MODULE_PATH)/$(MODULE_ZIP)
9 | rm $(MODULE_PATH)/$(MODULE_ZIP)
10 |
11 | clean:
12 | rm -rf build/
13 | rm -rf bin/
14 | rm -rf libs/
15 |
--------------------------------------------------------------------------------
/assets/README:
--------------------------------------------------------------------------------
1 | Place your assets like PNG files in this directory and they will be packaged
2 | with your module.
3 |
4 | All JavaScript files in the assets directory are IGNORED except if you create a
5 | file named "com.atticoos.tiokhttp.js" in this directory in which case it will be
6 | wrapped by native code, compiled, and used as your module. This allows you to
7 | run pure JavaScript modules that are pre-compiled.
8 |
9 | Note: Mobile Web does not support this assets directory.
10 |
--------------------------------------------------------------------------------
/android/assets/README:
--------------------------------------------------------------------------------
1 | Place your assets like PNG files in this directory and they will be packaged
2 | with your module.
3 |
4 | All JavaScript files in the assets directory are IGNORED except if you create a
5 | file named "com.atticoos.tiokhttp.js" in this directory in which case it will be
6 | wrapped by native code, compiled, and used as your module. This allows you to
7 | run pure JavaScript modules that are pre-compiled.
8 |
9 | Note: Mobile Web does not support this assets directory.
10 |
--------------------------------------------------------------------------------
/android/timodule.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
--------------------------------------------------------------------------------
/android/platform/README:
--------------------------------------------------------------------------------
1 | You can place platform-specific files here in sub-folders named "android" and/or "iphone", just as you can with normal Titanium Mobile SDK projects. Any folders and files you place here will be merged with the platform-specific files in a Titanium Mobile project that uses this module.
2 |
3 | When a Titanium Mobile project that uses this module is built, the files from this platform/ folder will be treated the same as files (if any) from the Titanium Mobile project's platform/ folder.
4 |
--------------------------------------------------------------------------------
/android/manifest:
--------------------------------------------------------------------------------
1 | #
2 | # this is your module manifest and used by Titanium
3 | # during compilation, packaging, distribution, etc.
4 | #
5 | version: 1.1.1
6 | apiversion: 2
7 | description: titanium-okhttp
8 | author: Your Name
9 | license: Specify your license
10 | copyright: Copyright (c) 2015 by Your Company
11 |
12 | # these should not be edited
13 | name: titanium-okhttp
14 | moduleid: com.atticoos.tiokhttp
15 | guid: 8f27f52f-2e2f-4bc2-a81e-a644caa66110
16 | platform: android
17 | minsdk: 3.4.0.GA
18 |
--------------------------------------------------------------------------------
/android/.project:
--------------------------------------------------------------------------------
1 |
2 |
3 | titanium-okhttp
4 |
5 |
6 |
7 |
8 |
9 | com.appcelerator.titanium.core.builder
10 |
11 |
12 |
13 |
14 | com.aptana.ide.core.unifiedBuilder
15 |
16 |
17 |
18 |
19 | org.eclipse.jdt.core.javabuilder
20 |
21 |
22 |
23 |
24 |
25 | org.eclipse.jdt.core.javanature
26 | com.appcelerator.titanium.mobile.module.nature
27 | com.aptana.projects.webnature
28 |
29 |
30 |
--------------------------------------------------------------------------------
/documentation/index.md:
--------------------------------------------------------------------------------
1 | # titanium-okhttp Module
2 |
3 | ## Description
4 |
5 | TODO: Enter your module description here
6 |
7 | ## Accessing the titanium-okhttp Module
8 |
9 | To access this module from JavaScript, you would do the following:
10 |
11 | var titanium_okhttp = require("com.atticoos.tiokhttp");
12 |
13 | The titanium_okhttp variable is a reference to the Module object.
14 |
15 | ## Reference
16 |
17 | TODO: If your module has an API, you should document
18 | the reference here.
19 |
20 | ### titanium_okhttp.function
21 |
22 | TODO: This is an example of a module function.
23 |
24 | ### titanium_okhttp.property
25 |
26 | TODO: This is an example of a module property.
27 |
28 | ## Usage
29 |
30 | TODO: Enter your usage example here
31 |
32 | ## Author
33 |
34 | TODO: Enter your author name, email and other contact
35 | details you want to share here.
36 |
37 | ## License
38 |
39 | TODO: Enter your license/legal information here.
40 |
--------------------------------------------------------------------------------
/android/src/com/atticoos/tiokhttp/TitaniumOkhttpModule.java:
--------------------------------------------------------------------------------
1 | /**
2 | * This file was auto-generated by the Titanium Module SDK helper for Android
3 | * Appcelerator Titanium Mobile
4 | * Copyright (c) 2009-2010 by Appcelerator, Inc. All Rights Reserved.
5 | * Licensed under the terms of the Apache Public License
6 | * Please see the LICENSE included with this distribution for details.
7 | *
8 | */
9 | package com.atticoos.tiokhttp;
10 |
11 | import org.appcelerator.kroll.KrollModule;
12 | import org.appcelerator.kroll.annotations.Kroll;
13 |
14 | import org.appcelerator.titanium.TiApplication;
15 | import org.appcelerator.kroll.common.TiConfig;
16 |
17 |
18 | @Kroll.module(name="TitaniumOkhttp", id="com.atticoos.tiokhttp")
19 | public class TitaniumOkhttpModule extends KrollModule
20 | {
21 |
22 | // Standard Debugging variables
23 | private static final String LCAT = "TitaniumOkhttpModule";
24 |
25 | public TitaniumOkhttpModule()
26 | {
27 | super();
28 | }
29 |
30 | @Kroll.onAppCreate
31 | public static void onAppCreate(TiApplication app) { }
32 | }
33 |
--------------------------------------------------------------------------------
/android/.classpath:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
--------------------------------------------------------------------------------
/example/app.js:
--------------------------------------------------------------------------------
1 | // This is a test harness for your module
2 | // You should do something interesting in this harness
3 | // to test out the module and to provide instructions
4 | // to users on how to use it by example.
5 |
6 |
7 | // open a single window
8 | var win = Ti.UI.createWindow({
9 | backgroundColor:'white'
10 | });
11 | var label = Ti.UI.createLabel();
12 | win.add(label);
13 | win.open();
14 |
15 | // TODO: write your module tests here
16 | var titanium_okhttp = require('com.atticoos.tiokhttp');
17 | Ti.API.info("module is => " + titanium_okhttp);
18 |
19 | label.text = titanium_okhttp.example();
20 |
21 | Ti.API.info("module exampleProp is => " + titanium_okhttp.exampleProp);
22 | titanium_okhttp.exampleProp = "This is a test value";
23 |
24 | if (Ti.Platform.name == "android") {
25 | var proxy = titanium_okhttp.createExample({
26 | message: "Creating an example Proxy",
27 | backgroundColor: "red",
28 | width: 100,
29 | height: 100,
30 | top: 100,
31 | left: 150
32 | });
33 |
34 | proxy.printMessage("Hello world!");
35 | proxy.message = "Hi world!. It's me again.";
36 | proxy.printMessage("Hello world!");
37 | win.add(proxy);
38 | }
39 |
40 |
--------------------------------------------------------------------------------
/android/example/app.js:
--------------------------------------------------------------------------------
1 | // This is a test harness for your module
2 | // You should do something interesting in this harness
3 | // to test out the module and to provide instructions
4 | // to users on how to use it by example.
5 |
6 |
7 | // open a single window
8 | var win = Ti.UI.createWindow({
9 | backgroundColor:'white'
10 | });
11 | var label = Ti.UI.createLabel();
12 | win.add(label);
13 | win.open();
14 |
15 | // TODO: write your module tests here
16 | var titanium_okhttp = require('com.atticoos.tiokhttp');
17 | Ti.API.info("module is => " + titanium_okhttp);
18 |
19 | label.text = titanium_okhttp.example();
20 |
21 | Ti.API.info("module exampleProp is => " + titanium_okhttp.exampleProp);
22 | titanium_okhttp.exampleProp = "This is a test value";
23 |
24 | if (Ti.Platform.name == "android") {
25 | var proxy = titanium_okhttp.createExample({
26 | message: "Creating an example Proxy",
27 | backgroundColor: "red",
28 | width: 100,
29 | height: 100,
30 | top: 100,
31 | left: 150
32 | });
33 |
34 | proxy.printMessage("Hello world!");
35 | proxy.message = "Hi world!. It's me again.";
36 | proxy.printMessage("Hello world!");
37 | win.add(proxy);
38 | }
39 |
40 |
--------------------------------------------------------------------------------
/android/build.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | Ant build script for Titanium Android module titanium-okhttp
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
--------------------------------------------------------------------------------
/android/src/com/atticoos/tiokhttp/HttpClientProxy.java:
--------------------------------------------------------------------------------
1 | package com.atticoos.tiokhttp;
2 |
3 | import java.util.HashMap;
4 | import org.appcelerator.kroll.KrollDict;
5 | import org.appcelerator.kroll.KrollProxy;
6 | import org.appcelerator.kroll.KrollFunction;
7 | import org.appcelerator.kroll.annotations.Kroll;
8 | import org.appcelerator.titanium.util.TiConfig;
9 | import java.util.*;
10 |
11 |
12 | @Kroll.proxy(creatableInModule=TitaniumOkhttpModule.class)
13 | public class HttpClientProxy extends KrollProxy
14 | {
15 | // Standard Debugging variables
16 | private static final String LCAT = "HttpClientProxy";
17 |
18 | private String requestMethod;
19 | private String requestUrl;
20 | private HashMap requestHeaders = new HashMap();
21 | private ProxyRequest request;
22 |
23 | public HttpClientProxy () {
24 | super();
25 | }
26 |
27 | @Kroll.getProperty @Kroll.method
28 | public String getResponseText () {
29 | if (this.request != null) {
30 | return this.request.getResponseText();
31 | } else {
32 | return null;
33 | }
34 | }
35 |
36 | @Kroll.method
37 | public void open (String method, String url) {
38 | this.requestMethod = method;
39 | this.requestUrl = url;
40 | }
41 |
42 | @Kroll.method
43 | public void setRequestHeader (String key, String value) {
44 | this.requestHeaders.put(key, value);
45 | }
46 |
47 | @Kroll.method
48 | public void send (@Kroll.argument(optional = true) String data) {
49 | this.request = new ProxyRequest(this);
50 | this.request.setHeaders(this.requestHeaders);
51 | this.request.setPostData(data);
52 |
53 | Object onload = this.getProperty("onload");
54 | Object onerror = this.getProperty("onerror");
55 |
56 | if (onload != null && onload instanceof KrollFunction) {
57 | this.request.setSuccessCallback((KrollFunction) onload);
58 | }
59 |
60 | if (onerror != null && onerror instanceof KrollFunction) {
61 | this.request.setErrorCallback((KrollFunction) onerror);
62 | }
63 |
64 | try {
65 | HttpClient.method(this.requestMethod, this.requestUrl, this.request);
66 | } catch (InvalidMethodException e) {
67 | this.request.fireErrorCallback(e.toString());
68 | }
69 | }
70 | }
71 |
--------------------------------------------------------------------------------
/android/src/com/atticoos/tiokhttp/OkHttpClientProxy.java:
--------------------------------------------------------------------------------
1 | package com.atticoos.tiokhttp;
2 |
3 |
4 | import java.util.HashMap;
5 |
6 | import org.appcelerator.kroll.KrollDict;
7 | import org.appcelerator.kroll.KrollProxy;
8 | import org.appcelerator.kroll.KrollFunction;
9 | import org.appcelerator.kroll.annotations.Kroll;
10 | import org.appcelerator.titanium.util.TiConfig;
11 | import java.util.*;
12 |
13 | @Kroll.proxy(creatableInModule=TitaniumOkhttpModule.class)
14 | public class OkHttpClientProxy extends KrollProxy
15 | {
16 | // Standard Debugging variables
17 | private static final String LCAT = "OkHttpClientProxy";
18 |
19 | private HashMap defaultHeaders = new HashMap();
20 |
21 | public OkHttpClientProxy () {
22 | super();
23 | }
24 |
25 | @Kroll.method
26 | public void setDefaultHeaders (HashMap args) {
27 | Iterator it = args.entrySet().iterator();
28 | while (it.hasNext()) {
29 | Map.Entry pairs = (Map.Entry) it.next();
30 | if (pairs.getKey() instanceof String && pairs.getValue() instanceof String) {
31 | this.defaultHeaders.put((String) pairs.getKey(), (String) pairs.getValue());
32 | }
33 | }
34 | }
35 |
36 | @Kroll.method
37 | public void GET (String url, HashMap args) {
38 | ProxyRequest request = new ProxyRequest(this, args, this.defaultHeaders);
39 | HttpClient.GET(url, request);
40 | }
41 |
42 | @Kroll.method
43 | public void POST (String url, HashMap args) {
44 | ProxyRequest request = new ProxyRequest(this, args, this.defaultHeaders);
45 | HttpClient.POST(url, request);
46 | }
47 |
48 | @Kroll.method
49 | public void PUT (String url, HashMap args) {
50 | ProxyRequest request = new ProxyRequest(this, args, this.defaultHeaders);
51 | HttpClient.PUT(url, request);
52 | }
53 |
54 | @Kroll.method
55 | public void PATCH (String url, HashMap args) {
56 | ProxyRequest request = new ProxyRequest(this, args, this.defaultHeaders);
57 | HttpClient.PATCH(url, request);
58 | }
59 |
60 | @Kroll.method
61 | public void DELETE (String url, HashMap args) {
62 | ProxyRequest request = new ProxyRequest(this, args, this.defaultHeaders);
63 | HttpClient.DELETE(url, request);
64 | }
65 |
66 | @Kroll.method
67 | public void HEAD (String url, HashMap args) {
68 | ProxyRequest request = new ProxyRequest(this, args, this.defaultHeaders);
69 | HttpClient.HEAD(url, request);
70 | }
71 | }
72 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # titanium-okhttp
2 | Titanium's native HTTP android module runs on an [Apache HTTP library from 2007](https://github.com/appcelerator/titanium_mobile/blob/58198c641d77e17d156431666e80bae732b5c130/android/titanium/src/thirdparty/org/apache/Commons-NOTICE.txt).
3 | The problem with [Ti.Network.HTTPClient](http://docs.appcelerator.com/titanium/3.0/#!/api/Titanium.Network.HTTPClient) is it's lack of support for some HTTP methods, mainly **no PATCH support**.
4 |
5 | `titanium-okhttp` introduces an interchangeable HTTP client that interfaces [okhttp](https://github.com/square/okhttp). As of Android 4.4, okhttp has been the supporting library. Let's get titanium up to speed!
6 |
7 | Note to [gittio](http://gitt.io) users: this module is still in development
8 |
9 | ## Installation
10 |
11 | #### With gittio
12 | ```
13 | gittio install com.atticoos.tiokhttp
14 | ```
15 |
16 | #### Without gittio
17 | Download the latest zip in `android/dist` and unzip in your project root such that it fills/creates a `modules` directory with its contents
18 |
19 | ## BC Integration
20 | You can seamlessly swap out your existing networking client for `titanium-okhttp`, and pick up where you left off. No refactoring.
21 |
22 | ```js
23 | var client,
24 | options = {
25 | onload: function () {
26 | // handle your response
27 | },
28 | onerror: function () {
29 | // handle your error
30 | }
31 | };
32 |
33 | var client
34 |
35 | if (Ti.Platform.osname === 'android') {
36 | client = require('com.atticoos.tiokhttp').createHttpClient(options);
37 | } else {
38 | client = Ti.Network.createHttpClient(options);
39 | }
40 |
41 | client.setRequestHeader('Content-Type', 'application/json; charset=utf8');
42 | client.open('GET', url);
43 | client.send(data);
44 | ```
45 |
46 | Nothing has changed, other than conditionally creating the client with a different library for android.
47 |
48 | ## A new interface
49 | If you're starting a new project and don't care to have backward compatability, you'll find a much nicer request API:
50 |
51 | An example `GET` request:
52 | ```js
53 | var client = TitaniumOkHttp.createOkHttpClient();
54 | client.GET(url, {
55 | onSuccess: function (data, status, headers) {
56 | // your response data
57 | }
58 | });
59 | ```
60 |
61 | An example `POST` request, with headers:
62 | ```js
63 | var client = TitaniumOkHttp.createOkHttpClient({
64 | defaultHeaders: {
65 | 'Content-Type': 'application/json'
66 | }
67 | });
68 | client.POST(url, {
69 | data: JSON.stringify({foo: 'bar'}),
70 | headers: {
71 | 'Authorization': 'Access-Token xxx'
72 | },
73 | onSuccess: function (data, status, headers) {
74 | // your response data
75 | },
76 | onError: function (error, status, headers) {
77 | // your error response data
78 | }
79 | });
80 | ```
81 |
--------------------------------------------------------------------------------
/android/documentation/index.md:
--------------------------------------------------------------------------------
1 | # titanium-okhttp
2 | Titanium's native HTTP android module runs on an [Apache HTTP library from 2007](https://github.com/appcelerator/titanium_mobile/blob/58198c641d77e17d156431666e80bae732b5c130/android/titanium/src/thirdparty/org/apache/Commons-NOTICE.txt).
3 | The problem with [Ti.Network.HTTPClient](http://docs.appcelerator.com/titanium/3.0/#!/api/Titanium.Network.HTTPClient) is it's lack of support for some HTTP methods, mainly **no PATCH support**.
4 |
5 | `titanium-okhttp` introduces an interchangeable HTTP client that interfaces [okhttp](https://github.com/square/okhttp). As of Android 4.4, okhttp has been the supporting library. Let's get titanium up to speed!
6 |
7 | Note to [gittio](http://gitt.io) users: this module is still in development
8 |
9 | ## Installation
10 |
11 | #### With gittio
12 | ```
13 | gittio install com.atticoos.tiokhttp
14 | ```
15 |
16 | #### Without gittio
17 | Download the latest zip in `android/dist` and unzip in your project root such that it fills/creates a `modules` directory with its contents
18 |
19 | ## BC Integration
20 | You can seamlessly swap out your existing networking client for `titanium-okhttp`, and pick up where you left off. No refactoring.
21 |
22 | ```js
23 | var client,
24 | options = {
25 | onload: function () {
26 | // handle your response
27 | },
28 | onerror: function () {
29 | // handle your error
30 | }
31 | };
32 |
33 | var client
34 |
35 | if (Ti.Platform.osname === 'android') {
36 | client = require('com.atticoos.tiokhttp').createHttpClient(options);
37 | } else {
38 | client = Ti.Network.createHttpClient(options);
39 | }
40 |
41 | client.setRequestHeader('Content-Type', 'application/json; charset=utf8');
42 | client.open('GET', url);
43 | client.send(data);
44 | ```
45 |
46 | Nothing has changed, other than conditionally creating the client with a different library for android.
47 |
48 | ## A new interface
49 | If you're starting a new project and don't care to have backward compatability, you'll find a much nicer request API:
50 |
51 | An example `GET` request:
52 | ```js
53 | var client = TitaniumOkHttp.createOkHttpClient();
54 | client.GET(url, {
55 | onSuccess: function (data, status, headers) {
56 | // your response data
57 | }
58 | });
59 | ```
60 |
61 | An example `POST` request, with headers:
62 | ```js
63 | var client = TitaniumOkHttp.createOkHttpClient({
64 | defaultHeaders: {
65 | 'Content-Type': 'application/json'
66 | }
67 | });
68 | client.POST(url, {
69 | data: JSON.stringify({foo: 'bar'}),
70 | headers: {
71 | 'Authorization': 'Access-Token xxx'
72 | },
73 | onSuccess: function (data, status, headers) {
74 | // your response data
75 | },
76 | onError: function (error, status, headers) {
77 | // your error response data
78 | }
79 | });
80 | ```
81 |
--------------------------------------------------------------------------------
/android/src/com/atticoos/tiokhttp/HttpClient.java:
--------------------------------------------------------------------------------
1 | package com.atticoos.tiokhttp;
2 |
3 | import com.squareup.okhttp.MediaType;
4 | import com.squareup.okhttp.OkHttpClient;
5 | import com.squareup.okhttp.Request;
6 | import com.squareup.okhttp.RequestBody;
7 | import com.squareup.okhttp.Response;
8 | import com.squareup.okhttp.ResponseBody;
9 | import com.squareup.okhttp.Callback;
10 | import com.squareup.okhttp.Headers;
11 | import org.appcelerator.kroll.KrollFunction;
12 | import org.appcelerator.kroll.KrollProxy;
13 | import org.appcelerator.kroll.common.Log;
14 |
15 | import java.io.IOException;
16 | import java.lang.reflect.Method;
17 | import java.util.HashMap;
18 | import java.util.Iterator;
19 | import java.util.Map;
20 |
21 | class HttpClient
22 | {
23 | private static final String LCAT = "TitaniumHttpClient";
24 |
25 | public static void GET (String url, final ProxyRequest proxyRequest) {
26 | Request.Builder request = new Request.Builder().url(url);
27 | HttpClient.send(request, proxyRequest);
28 | }
29 |
30 | public static void POST (String url, final ProxyRequest proxyRequest) {
31 | RequestBody requestBody = RequestBody.create(proxyRequest.getMediaType(), proxyRequest.getPostData());
32 | Request.Builder request = new Request.Builder().url(url).post(requestBody);
33 | HttpClient.send(request, proxyRequest);
34 | }
35 |
36 | public static void PUT (String url, final ProxyRequest proxyRequest) {
37 | RequestBody requestBody = RequestBody.create(proxyRequest.getMediaType(), proxyRequest.getPostData());
38 | Request.Builder request = new Request.Builder().url(url).put(requestBody);
39 | HttpClient.send(request, proxyRequest);
40 | }
41 |
42 | public static void PATCH (String url, final ProxyRequest proxyRequest) {
43 | RequestBody requestBody = RequestBody.create(proxyRequest.getMediaType(), proxyRequest.getPostData());
44 | Request.Builder request = new Request.Builder().url(url).patch(requestBody);
45 | HttpClient.send(request, proxyRequest);
46 | }
47 |
48 | public static void DELETE (String url, final ProxyRequest proxyRequest) {
49 | Request.Builder request = new Request.Builder().url(url);
50 | if (proxyRequest.hasPostData()) {
51 | // workaround until https://github.com/square/okhttp/pull/1317
52 | RequestBody requestBody = RequestBody.create(proxyRequest.getMediaType(), proxyRequest.getPostData());
53 | request.method("DELETE", requestBody);
54 | } else {
55 | request.delete();
56 | }
57 | HttpClient.send(request, proxyRequest);
58 | }
59 |
60 | public static void HEAD (String url, final ProxyRequest proxyRequest) {
61 | Request.Builder request = new Request.Builder().url(url).head();
62 | HttpClient.send(request, proxyRequest);
63 | }
64 |
65 | /**
66 | * Send a request by supplying the request method as a String and uses reflection to execute the proper request
67 | *
68 | * @param methodString
69 | * @param url
70 | * @param proxyRequest
71 | * @throws InvalidMethodException
72 | */
73 | public static void method (String methodString, String url, final ProxyRequest proxyRequest) throws InvalidMethodException {
74 | try {
75 | methodString = methodString.toUpperCase().trim();
76 | Method method = HttpClient.class.getDeclaredMethod(methodString, String.class, ProxyRequest.class);
77 | method.invoke(null, url, proxyRequest);
78 | } catch (Exception e) {
79 | e.printStackTrace();
80 | throw new InvalidMethodException(methodString);
81 | }
82 | }
83 |
84 | private static void send (Request.Builder request, final ProxyRequest proxyRequest) {
85 | final OkHttpClient client = new OkHttpClient();
86 |
87 | if (proxyRequest.hasHeaders()) {
88 | Iterator it = proxyRequest.getHeaders().entrySet().iterator();
89 | while (it.hasNext()) {
90 | Map.Entry pairs = (Map.Entry) it.next();
91 | request.header(pairs.getKey(), pairs.getValue());
92 | }
93 | }
94 |
95 | client.newCall(request.build()).enqueue(new Callback () {
96 |
97 | @Override
98 | public void onFailure (Request request, IOException e) {
99 | e.printStackTrace();
100 | if (proxyRequest.hasErrorCallback()) {
101 | proxyRequest.fireErrorCallback(null, null, null);
102 | }
103 | }
104 |
105 | @Override
106 | public void onResponse (Response response) {
107 | String bodyString;
108 | Headers responseHeaders = response.headers();
109 | HashMap headerMap = new HashMap();
110 |
111 | for (int i = 0; i < responseHeaders.size(); i++) {
112 | headerMap.put(responseHeaders.name(i), responseHeaders.value(i));
113 | }
114 |
115 | try {
116 | ResponseBody body = response.body();
117 | bodyString = body.string();
118 | } catch (IOException e) {
119 | bodyString = "";
120 | }
121 |
122 | if (response.isSuccessful() && proxyRequest.hasSuccessCallback()) {
123 | proxyRequest.fireSuccessCallback(bodyString, response.code(), headerMap);
124 | } else if (!response.isSuccessful() && proxyRequest.hasErrorCallback()) {
125 | proxyRequest.fireErrorCallback(bodyString, response.code(), headerMap);
126 | }
127 | }
128 | });
129 | }
130 | }
131 |
--------------------------------------------------------------------------------
/android/src/com/atticoos/tiokhttp/ProxyRequest.java:
--------------------------------------------------------------------------------
1 | package com.atticoos.tiokhttp;
2 |
3 | import java.util.HashMap;
4 | import java.util.Map;
5 | import java.util.Iterator;
6 |
7 | import org.appcelerator.kroll.KrollFunction;
8 | import org.appcelerator.kroll.KrollProxy;
9 |
10 | import com.squareup.okhttp.MediaType;
11 |
12 | class ProxyRequest
13 | {
14 | private final String KEY_ON_SUCCESS = "onSuccess";
15 | private final String KEY_ON_FAILURE = "onError";
16 | private final String KEY_POSTDATA = "data";
17 | private final String KEY_HEADERS = "headers";
18 |
19 | private String postData = new String(); // https://github.com/square/okhttp/pull/1558
20 | private String responseText;
21 | private KrollProxy proxy;
22 | private HashMap headers;
23 | private KrollFunction successCallback;
24 | private KrollFunction errorCallback;
25 |
26 | public ProxyRequest(KrollProxy proxy) {
27 | this(proxy, null, null);
28 | }
29 |
30 | public ProxyRequest (KrollProxy proxy, HashMap proxyArgs) {
31 | this(proxy, proxyArgs, null);
32 | }
33 |
34 | public ProxyRequest (KrollProxy proxy, HashMap proxyArgs, HashMap defaultHeaders) {
35 | this.proxy = proxy;
36 |
37 | if (defaultHeaders == null) {
38 | this.headers = new HashMap();
39 | } else {
40 | this.headers = defaultHeaders;
41 | }
42 |
43 | if (proxyArgs != null) {
44 | Object object;
45 | if (proxyArgs.containsKey(KEY_ON_SUCCESS)) {
46 | object = proxyArgs.get(KEY_ON_SUCCESS);
47 | if (object instanceof KrollFunction) {
48 | this.successCallback = (KrollFunction) object;
49 | }
50 | }
51 |
52 | if (proxyArgs.containsKey(KEY_ON_FAILURE)) {
53 | object = proxyArgs.get(KEY_ON_FAILURE);
54 | if (object instanceof KrollFunction) {
55 | this.errorCallback = (KrollFunction) object;
56 | }
57 | }
58 |
59 | if (proxyArgs.containsKey(KEY_POSTDATA)) {
60 | object = proxyArgs.get(KEY_POSTDATA);
61 | if (object instanceof String) {
62 | this.setPostData((String) object);
63 | }
64 | }
65 |
66 | if (proxyArgs.containsKey(KEY_HEADERS)) {
67 | object = proxyArgs.get(KEY_HEADERS);
68 | if (object instanceof HashMap) {
69 | this.buildHeaders((HashMap) object);
70 | }
71 | }
72 | }
73 | }
74 |
75 | private void buildHeaders (HashMap headers) {
76 | Iterator it = headers.entrySet().iterator();
77 | while (it.hasNext()) {
78 | Map.Entry pairs = (Map.Entry) it.next();
79 | if (pairs.getKey() instanceof String && pairs.getValue() instanceof String) {
80 | this.headers.put((String) pairs.getKey(), (String) pairs.getValue());
81 | }
82 | }
83 | }
84 |
85 | public boolean hasHeaders () {
86 | return !this.headers.isEmpty();
87 | }
88 |
89 | public HashMap getHeaders () {
90 | return this.headers;
91 | }
92 |
93 | public void setHeaders (HashMap headers) {
94 | this.headers = headers;
95 | }
96 |
97 | public void addHeader(String key, String value) {
98 | this.headers.put(key, value);
99 | }
100 |
101 | public boolean hasPostData () {
102 | return this.postData != null && !this.postData.isEmpty();
103 | }
104 |
105 | public String getPostData () {
106 | return this.postData;
107 | }
108 |
109 | public void setPostData (String postData) {
110 | // ensure the postData is never null, as OkHTTP may only consume non nulls at this time
111 | this.postData = (null == postData ? "" : postData);
112 | }
113 |
114 | public boolean hasContentType () {
115 | return this.headers.containsKey("Content-Type") || this.headers.containsKey("content-type");
116 | }
117 |
118 | public String getContentType () {
119 | if (this.headers.containsKey("Content-Type")) {
120 | return this.headers.get("Content-Type");
121 | } else if (this.headers.containsKey("content-type")) {
122 | return this.headers.get("content-type");
123 | } else {
124 | return null;
125 | }
126 | }
127 |
128 | public MediaType getMediaType () {
129 | if (this.hasContentType()) {
130 | return MediaType.parse(this.getContentType());
131 | } else {
132 | return MediaType.parse("");
133 | }
134 | }
135 |
136 | public boolean hasSuccessCallback () {
137 | return this.successCallback != null;
138 | }
139 |
140 | public void fireSuccessCallback (String responseData, Integer statusCode, HashMap headers) {
141 | this.responseText = responseData;
142 | this.successCallback.call(this.proxy.getKrollObject(), new Object[]{responseData, statusCode, headers});
143 | }
144 |
145 | public void setSuccessCallback (KrollFunction callback) {
146 | this.successCallback = callback;
147 | }
148 |
149 | public boolean hasErrorCallback () {
150 | return this.errorCallback != null;
151 | }
152 |
153 | public void fireErrorCallback (String responseData) {
154 | this.fireErrorCallback(responseData, null, null);
155 | }
156 |
157 | public void fireErrorCallback (String responseData, Integer statusCode, HashMap headers) {
158 | this.responseText = responseData;
159 | this.errorCallback.call(this.proxy.getKrollObject(), new Object[]{responseData, statusCode, headers});
160 | }
161 |
162 | public void setErrorCallback (KrollFunction callback) {
163 | this.errorCallback = callback;
164 | }
165 |
166 | public String getResponseText () {
167 | return this.responseText;
168 | }
169 | }
--------------------------------------------------------------------------------