net.phalapi.sdk.PhalApiClient.java Source code

Java tutorial

Introduction

Here is the source code for net.phalapi.sdk.PhalApiClient.java

Source

package net.phalapi.sdk;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import org.json.JSONObject;

import android.util.Log;

/**
 * PhalApiSDKJAVA
 *
 * - ?ASQL???
 * - ???
 * 
 * <br><br>
 ```
 * PhalApiClientResponse response = PhalApiClient.create()
 *   .withHost("http://demo.phalapi.net/")
 *   .withService("Default.Index")
 *   .withParams("name", "dogstar")
 *   .withTimeout(3000)
 *   .request();
 *
 * Log.v("response ret", response.getRet() + "");
 * Log.v("response data", response.getData());
 * Log.v("response msg", response.getMsg());
```
*
* @package     PhalApi\Response
* @license     http://www.phalapi.net/license GPL ??
* @link        http://www.phalapi.net/
* @author      dogstar <chanzonghuang@gmail.com> 2015-10-16
 */

public class PhalApiClient {

    protected String host;
    protected PhalApiClientFilter filter;
    protected PhalApiClientParser parser;
    protected String service;
    protected int timeoutMs;
    protected Map<String, String> params;

    /**
     * ?????
     * @return PhalApiClient
     */
    public static PhalApiClient create() {
        return new PhalApiClient();
    }

    protected PhalApiClient() {
        this.host = "";
        this.reset();

        this.parser = new PhalApiClientParserJson();
    }

    /**
     * ???
     * @param String host
     * @return PhalApiClient
     */
    public PhalApiClient withHost(String host) {
        this.host = host;
        return this;
    }

    /**
     * ?DI().filter
     * @param PhalApiClientFilter filter 
     * @return PhalApiClient
     */
    public PhalApiClient withFilter(PhalApiClientFilter filter) {
        this.filter = filter;
        return this;
    }

    /**
     * ??JSON???
     * @param PhalApiClientParser parser ?
     * @return PhalApiClient
     */
    public PhalApiClient withParser(PhalApiClientParser parser) {
        this.parser = parser;
        return this;
    }

    /**
     * ????????????
     * @return PhalApiClient
     */
    public PhalApiClient reset() {
        this.service = "";
        this.timeoutMs = 3000;
        this.params = new HashMap<String, String>();

        return this;
    }

    /**
     * ????Default.Index
     * @param String service ????
     * @return PhalApiClient
     */
    public PhalApiClient withService(String service) {
        this.service = service;
        return this;
    }

    /**
     * ?????
     * @param String name ???
     * @param String value 
     * @return PhalApiClient
     */
    public PhalApiClient withParams(String name, String value) {
        this.params.put(name, value);
        return this;
    }

    /**
     * ??
     * @param int timeoutMS ??
     * @return PhalApiClient
     */
    public PhalApiClient withTimeout(int timeoutMS) {
        this.timeoutMs = timeoutMS;
        return this;
    }

    /**
     * ??
     * @return PhalApiClientResponse
     */
    public PhalApiClientResponse request() {
        String url = this.host;

        if (this.service != null && this.service.length() > 0) {
            url += "?service=" + this.service;
        }
        if (this.filter != null) {
            this.filter.filter(this.service, this.params);
        }

        try {
            String rs = this.doRequest(url, this.params, this.timeoutMs);
            return this.parser.parse(rs);
        } catch (Exception ex) {
            return new PhalApiClientResponse(408, "", ex.getMessage());
        }
    }

    protected String doRequest(String requestUrl, Map<String, String> params, int timeoutMs) throws Exception {
        String result = null;
        URL url = null;
        HttpURLConnection connection = null;
        InputStreamReader in = null;

        url = new URL(requestUrl);
        connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setRequestMethod("POST"); // ?
        connection.setUseCaches(false);
        connection.setConnectTimeout(timeoutMs);

        DataOutputStream out = new DataOutputStream(connection.getOutputStream());

        //POST?
        String postContent = "";
        Iterator<Entry<String, String>> iter = params.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry<String, String> entry = (Map.Entry<String, String>) iter.next();
            postContent += "&" + entry.getKey() + "=" + entry.getValue();
        }
        out.writeBytes(postContent);
        out.flush();
        out.close();

        Log.d("[PhalApiClient requestUrl]", requestUrl + postContent);

        in = new InputStreamReader(connection.getInputStream());
        BufferedReader bufferedReader = new BufferedReader(in);
        StringBuffer strBuffer = new StringBuffer();
        String line = null;
        while ((line = bufferedReader.readLine()) != null) {
            strBuffer.append(line);
        }
        result = strBuffer.toString();

        Log.d("[PhalApiClient apiResult]", result);

        if (connection != null) {
            connection.disconnect();
        }

        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return result;
    }
}