Java tutorial
/* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.pedox.plugin.HttpClient; import org.apache.cordova.CordovaWebView; import org.apache.cordova.CallbackContext; import org.apache.cordova.CordovaPlugin; import org.apache.cordova.CordovaInterface; import org.apache.http.Header; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.app.Activity; import android.util.Base64; import android.util.Log; import com.loopj.android.http.AsyncHttpClient; import com.loopj.android.http.FileAsyncHttpResponseHandler; import com.loopj.android.http.RequestParams; import com.loopj.android.http.TextHttpResponseHandler; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.Iterator; public class HttpClient extends CordovaPlugin { /** * Constructor. */ public HttpClient() { } /** * Sets the context of the Command. This can then be used to do things like * get file paths associated with the Activity. * * @param cordova The context of the main Activity. * @param webView The CordovaWebView Cordova is running in. */ public void initialize(CordovaInterface cordova, CordovaWebView webView) { super.initialize(cordova, webView); } /** * Executes the request and returns PluginResult. * * @param action The action to execute. * @param args JSONArry of arguments for the plugin. * @param callbackContext The callback id used when calling back into JavaScript. * @return True if the action was valid, false if not. */ public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException { final Activity context = this.cordova.getActivity(); if (action.equals("get")) { this.getRequest(context, args.getString(0), args.getJSONObject(1), callbackContext); return true; } if (action.equals("image")) { this.getImage(context, args.getString(0), args.getJSONObject(1), callbackContext); return true; } if (action.equals("post")) { JSONObject data = args.getJSONObject(1); RequestParams params = new RequestParams(); for (Iterator<String> i = data.keys(); i.hasNext();) { String key = i.next(); try { Object value = data.get(key); params.put(key, value); } catch (JSONException e) { // Something went wrong! } } this.postRequest(context, args.getString(0), args.getJSONObject(2), params, callbackContext); return true; } if (action.equals("test")) { callbackContext.success("it works !"); } else { return false; } return true; } /** * Get request * @param context * @param url * @param callbackContext */ private void getRequest(final Activity context, String url, JSONObject options, final CallbackContext callbackContext) throws JSONException { final AsyncHttpClient client = new AsyncHttpClient(); this.setArgument(client, options); client.get(url, new TextHttpResponseHandler() { @Override public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) { HttpClient.handleResult(false, statusCode, headers, responseString, callbackContext, throwable); } @Override public void onSuccess(int statusCode, Header[] headers, String responseString) { HttpClient.handleResult(true, statusCode, headers, responseString, callbackContext, null); } }); } /** * Post Request * @param context * @param url * @param params * @param callbackContext */ public void postRequest(final Activity context, String url, JSONObject options, RequestParams params, final CallbackContext callbackContext) throws JSONException { final AsyncHttpClient client = new AsyncHttpClient(); this.setArgument(client, options); client.post(url, params, new TextHttpResponseHandler() { @Override public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) { HttpClient.handleResult(false, statusCode, headers, responseString, callbackContext, throwable); } @Override public void onSuccess(int statusCode, Header[] headers, String responseString) { HttpClient.handleResult(true, statusCode, headers, responseString, callbackContext, null); } }); } public void getImage(final Activity context, String url, JSONObject options, final CallbackContext callbackContext) throws JSONException { final AsyncHttpClient client = new AsyncHttpClient(); this.setArgument(client, options); client.get(url, new FileAsyncHttpResponseHandler(context) { @Override public void onFailure(int statusCode, Header[] headers, Throwable throwable, File file) { HttpClient.handleResult(false, statusCode, headers, "kekacauan", callbackContext, throwable); } @Override public void onSuccess(int statusCode, Header[] headers, File file) { InputStream inputStream = null; try { inputStream = new FileInputStream(file.getPath()); } catch (FileNotFoundException e) { e.printStackTrace(); } byte[] bytes; byte[] buffer = new byte[8192]; int bytesRead; ByteArrayOutputStream output = new ByteArrayOutputStream(); try { while ((bytesRead = inputStream.read(buffer)) != -1) { output.write(buffer, 0, bytesRead); } } catch (IOException e) { e.printStackTrace(); } bytes = output.toByteArray(); String encodedImage = Base64.encodeToString(bytes, Base64.DEFAULT); HttpClient.handleResult(true, statusCode, headers, encodedImage, callbackContext, null); } }); } private static void handleResult(boolean success, int statusCode, Header[] headers, String responseString, CallbackContext callbackContext, Throwable throwable) { JSONObject result = new JSONObject(); try { /** Set header **/ JSONObject headerParam = new JSONObject(); if (headers != null) { for (Header param : headers) { headerParam.put(param.getName(), param.getValue()); } } if (throwable != null) { result.put("error", throwable.getMessage()); } result.put("result", responseString); result.put("code", statusCode); result.put("header", headerParam); if (success == true) { callbackContext.success(result); } else { callbackContext.error(result); } } catch (JSONException e) { callbackContext.error(0); e.printStackTrace(); } } /** * Set Header Param * * @param client * @return */ private AsyncHttpClient setArgument(AsyncHttpClient client, JSONObject options) throws JSONException { client.setUserAgent( "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2243.0 Safari/537.36"); try { if (options.has("noRedirect")) { Log.v("[NOREDIRECT]", "Active"); client.setEnableRedirects(false); } JSONObject _headers = options.getJSONObject("headers"); for (Iterator<String> i = _headers.keys(); i.hasNext();) { String key = i.next(); try { Object value = _headers.get(key); client.addHeader(key, (String) value); } catch (JSONException e) { // Something went wrong! } } } catch (JSONException e) { } return client; } }