Showing posts with label post. Show all posts
Showing posts with label post. Show all posts

Thursday, December 5, 2013

POSTing json data with php cURL


<?php
$params = array(
    "id" => 1,
    "name" => "Pritom Kumar Mondal"
);
$param = json_encode($params);
$ch   = curl_init("http://localhost/api_server/user");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $param);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json',
    'Content-Length: ' . strlen($param))
);
$response = curl_exec($ch);
print_r($response);
?>

Tuesday, July 30, 2013

Java - Call URL And Sending HTTP Parameters Via GET POST PUT PATCH DELETE Method Easily Execute

Its very easy to invoke URL using Java, We can now send GET, POST, PUT, PATCH And Delete method easily. Invoking URL in Java is easy now. Call URL and get response from that URL is can be done using Java code.

package common;

import java.io.*;
import java.lang.reflect.Field;
import java.net.*;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;

/**
 * Created by pritom on 11/07/2016.
 */
public abstract class HttpJavaClient {    
    public static enum Method {
        GET, POST, PUT, PATCH, DELETE
    }

    public static enum Type {
        XML, JSON, URL_ENCODED;
    }
    ;

    public static void main(String[] args) throws Exception {
        Response response = doGet("https://pritomkumar.blogspot.com");
        println("Get_Result:\n" + lengthString(response.toString().replace("\n", ""), 400) + "...");

        Map params = new HashMap();
        params.put("param1", "Param1 value");
        params.put("param2", "Param2 value");

        response = doPost("https://pritomkumar.blogspot.com", buildParameters(params), Type.URL_ENCODED);
        println("Post_Result:\n" + lengthString(response.toString().replace("\n", ""), 400) + "...");
    }

    public static Response doGet(String url) {
        return execute(url, Method.GET, "", Type.URL_ENCODED);
    }

    public static Response doGet(String url, Map headers) {
        return execute(url, Method.GET, "", Type.URL_ENCODED, headers, null);
    }

    public static Response doPost(String url, String data, Type type) {
        return execute(url, Method.POST, data, type);
    }

    public static Response doPost(String url, String data, Type type, Map headers) {
        return execute(url, Method.POST, data, type, headers, null);
    }

    public static Response doPut(String url, String data, Type type) {
        return execute(url, Method.PUT, data, type);
    }

    public static Response doPut(String url, String data, Type type, Map headers) {
        return execute(url, Method.PUT, data, type, headers, null);
    }

    public static Response doPatch(String url, String data, Type type) {
        return execute(url, Method.PATCH, data, type);
    }

    public static Response doPatch(String url, String data, Type type, Map headers) {
        return execute(url, Method.PATCH, data, type, headers, null);
    }

    public static Response doDelete(String url) {
        return execute(url, Method.DELETE, "", Type.URL_ENCODED);
    }

    public static Response doDelete(String url, Map headers) {
        return execute(url, Method.DELETE, "", Type.URL_ENCODED, headers, null);
    }

    public static Response execute(String url, Method method, String data, Type type) {
        return execute(url, method, data, type, null, null);
    }

    private static Response execute(String requestURL, Method requestMethod, String requestData, Type dataType, Map headers, Integer timeOutMilli) {
        Long started = System.currentTimeMillis();
        String httpResponse = "", responseMessage = "";
        Integer httpCode = 0;
        timeOutMilli = timeOutMilli == null ? 1000 * 30 : timeOutMilli; /* Default read & write timeout */

        HttpsURLConnection connection = null;
        try {
            String contentType = "", accept = "", contentLength = "" + requestData.length();
            switch (dataType) {
                case XML:
                    contentType = "text/xml; charset=utf-8";
                    accept = "text/xml";
                    break;
                case JSON:
                    contentType = "application/json";
                    break;
                case URL_ENCODED:
                    contentType = "application/x-www-form-urlencoded";
                    break;
            }

            connection = (HttpsURLConnection) new URL(requestURL).openConnection();
            setRequestMethod(connection, requestMethod.name());
            connection.setDoOutput(true);
            connection.setConnectTimeout(timeOutMilli);
            connection.setReadTimeout(timeOutMilli);
            connection.setRequestProperty("Pragma", "no-cache");

            if (headers != null && headers.size() > 0) {
                for (Object name : headers.keySet().toArray()) {
                    if (name.toString().endsWith("tls")) {
                        //headers.put("tls", "TLSv1.2");
                        //headers.put("tls", "TLSv1");
                        SSLContext sc = SSLContext.getInstance(headers.get(name.toString()).toString());
                        sc.init(null, null, new java.security.SecureRandom()); 
                        connection.setSSLSocketFactory(sc.getSocketFactory());
                    }
                    else {
                        connection.setRequestProperty(name.toString(), headers.get(name.toString()).toString());
                    }
                }
            }

            if (requestData.length() > 0) {
                connection.setDoInput(true);

                if (accept.length() > 0) {
                    connection.setRequestProperty("Accept", accept);
                }
                if (contentType.length() > 0) {
                    connection.setRequestProperty("Content-Type", contentType);
                }

                connection.setRequestProperty("Content_length", contentLength);
                OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
                writer.write(requestData);
                writer.flush();
                writer.close();
            }

            httpCode = connection.getResponseCode();
            responseMessage = connection.getResponseMessage();
            InputStream is = null;

            if (httpCode >= 200 && httpCode <= 299) {
                is = connection.getInputStream();
            }
            else {
                is = connection.getErrorStream();
            }

            Writer writer5 = new StringWriter();
            char[] buffer = new char[1024];
            try {
                Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                int n;
                while ((n = reader.read(buffer)) != -1) {
                    writer5.write(buffer, 0, n);
                }
                httpResponse = writer5.toString();
            }
            catch (Exception ex) {
                httpResponse = "";
                responseMessage = ex.getMessage();
            }
        }
        catch (Exception ex) {
            httpResponse = "";
            responseMessage = ex.getMessage();
        }
        finally {
            try {
                connection.disconnect();
            }
            catch (Exception ex10) {
            }
        }

        return new Response(requestURL, httpCode, responseMessage, httpResponse, (System.currentTimeMillis() - started));
    }

    /* JAVA - HttpURLConnection Invalid HTTP method such as 'PATCH' */
    private static void setRequestMethod(final HttpsURLConnection httpURLConnection, final String method) throws Exception {
        try {
            httpURLConnection.setRequestMethod(method);
        }
        catch (final ProtocolException pe) {
            Class<?> connectionClass = httpURLConnection.getClass();
            Field delegateField = null;
            try {
                delegateField = connectionClass.getDeclaredField("delegate");
                delegateField.setAccessible(true);
                HttpsURLConnection delegateConnection = (HttpsURLConnection) delegateField.get(httpURLConnection);
                setRequestMethod(delegateConnection, method);
            }
            catch (NoSuchFieldException e) {
                // Ignore for now, keep going
            }
            catch (IllegalArgumentException e) {
                throw new RuntimeException(e);
            }
            catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            }
            try {
                Field methodField;
                while (connectionClass != null) {
                    try {
                        methodField = connectionClass.getDeclaredField("method");
                    }
                    catch (NoSuchFieldException e) {
                        connectionClass = connectionClass.getSuperclass();
                        continue;
                    }
                    methodField.setAccessible(true);
                    methodField.set(httpURLConnection, method);
                    break;
                }
            }
            catch (final Exception e) {
                throw new RuntimeException(e);
            }
        }
    }

    public static String buildParameters(Map parametersMap) {
        Iterator nameIterator = parametersMap.keySet().iterator();
        StringBuffer buf = new StringBuffer();

        while (nameIterator.hasNext()) {
            Object key = nameIterator.next();
            Object value = parametersMap.get(key);
            if (value == null) {
                value = "";
            }

            if (!(key instanceof String)) {
                throw new IllegalArgumentException("Expected a string key in parametersMap but found " + key);
            }

            if (!(value instanceof String)) {
                throw new IllegalArgumentException("Expected a string value in parametersMap but found " + value);
            }

            String parameterName = (String) key;
            String parameterValue = (String) value;
            if (buf.length() > 0) {
                buf.append('&');
            }

            try {
                buf.append(parameterName);
                buf.append('=');
                buf.append(URLEncoder.encode(parameterValue, "UTF-8"));
            }
            catch (Exception var9) {
                var9.printStackTrace();
            }
        }

        return buf.toString();
    }

    public static void parseParameters(String s, String enc, Map parameters) {
        if (s != null) {
            int start = 0;
            int end = s.length();
            boolean amp = true;

            do {
                int amp1 = s.indexOf(38, start);
                if (amp1 == -1) {
                    amp1 = end;
                }

                int eq = s.indexOf(61, start);
                if (eq == -1 || eq > amp1) {
                    eq = amp1;
                }

                String name = s.substring(start, eq);
                String value = eq == amp1 ? "" : s.substring(eq + 1, amp1);

                try {
                    parameters.put(URLDecoder.decode(name, enc), URLDecoder.decode(value, enc));
                }
                catch (Exception var11) {
                    var11.printStackTrace();
                }

                start = amp1 + 1;
            } while (start < end);
        }
    }

    public static class Response {
        private String url;
        private Integer code;
        private String message;
        private String body;
        private Long time;

        public Response(String url, Integer code, String message, String body, Long time) {
            this.url = url;
            this.code = code;
            this.message = message;
            this.body = body;
            this.time = time;
        }

        @Override
        public String toString() {
            return "{URL=" + this.url + ",Code=" + this.code + ", Message=" + this.message + ", Time=" + this.time + " Millis, Body=" + this.body + "}";
        }

        public Integer getCode() {
            return this.code;
        }

        public String getMessage() {
            return this.message;
        }

        public String getBody() {
            return this.body;
        }

        public Long getTime() {
            return this.time;
        }
    }

    public static void println(Object o) {
        System.out.println("" + o);
    }

    public static String lengthString(String s, Integer m) {
        return s.length() > m ? s.substring(0, m) : s;
    }
}

Saturday, June 22, 2013

PHP - Redirect and send data via POST

It is a simple way to do that.
Suppose you are in from.php, just call the function like:
<?php
actionPost("www.pritom.com/to.php", array(
    "id" => 1,
    "name" => "Pritom K Mondal";
)); 
?>
And suppose in to.php, write the following code:
<?php
print_r($_POST);
?>

That will output:

<?php
Array
(
    [id] => 1
    [name] => Pritom K Mondal
)
?>


<?php
function actionPost($action, $data = array()) 
{
    ?><html xmlns="http://www.w3.org/1999/xhtml">
        <head>
            <script type="text/javascript">
                function closethisasap (){
                    document.forms["redirectpost"].submit();
                }
            </script>
            <body onload="closethisasap();">
                <form name="redirectpost" method="post" action="<?php echo $action; ?>" >
                    <?php
                    if (!is_null($data)) {
                        foreach ($data as $k => $v) {
                            ?><input type="hidden" name="<?php echo $k; ?>" value="<?php echo $v; ?>" /><?php
                        }
                    }
                    ?>
                </form>
            </body>
        </head>
    </html>
    <?php exit();
}
?>

Thursday, April 18, 2013

Java - sending HTTP parameters via POST method Using HttpClient


HttpClient client = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://something.com/login");
List<NameValuePair> list = new ArrayList<NameValuePair>();
list.add(new BasicNameValuePair("username", "username"));
list.add(new BasicNameValuePair("password", "password"));
httppost.setEntity(new UrlEncodedFormEntity(list));

HttpResponse response = client.execute(httppost);
System.out.println("STATUS LINE: "+response.getStatusLine());
System.out.println("STATUS PHRASE: "+response.getStatusLine().getReasonPhrase());
System.out.println("STATUS METHOD: "+httppost.getMethod());
HttpEntity entity = response.getEntity();

if (entity != null) {
    System.out.println("CONTENT:\n");    
    InputStream inputStream = entity.getContent();
    BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
    String line;
    while ((line = br.readLine()) != null) {
        System.out.println("LINE: "+line);
    }
    br.close();
}

Friday, January 18, 2013

jQuery post call using ajax

jQuery.ajax({
    type: "POST",
    url: "http://domain.com/save_form_data",
    data: jQuery("form").serializeArray(),
    success: function(data) {
        console.log(data);
        alert("Success");
    },
    error: function() {
       alert("Error occurred."); 
    }
});

Tuesday, May 15, 2012

Execute Curl to GET POST PUT PATCH DELETE Method Using Php

$headers[] = "Authorization: Basic xxx";
$headers[] = "Accept: text/xml";

$post = array(
    "name" => "Some name",
    "roll" => "Some roll"

);

$result = CurlExecutor::execute("...com/api/test", "POST", $post, null, $headers);
CurlExecutor::prettyPrint($result);


<?php
class CurlExecutor
{
    static function execute($url, $method = "GET", $posts = null, $gets = null, $headers = null, Closure $closure = null)
    {
        $ch = curl_init();
        if ($gets != null) {
            $url .= "?" . (is_array($gets) ? self::makeRawQuery($gets) : $gets);
        }
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        if ($posts != null) {
            curl_setopt($ch, CURLOPT_POSTFIELDS, is_array($posts) ? self::makeRawQuery($posts) : $posts);
        }
        if ($method == "POST") {
            curl_setopt($ch, CURLOPT_POST, true);
        } else if ($method == "HEAD") {
            curl_setopt($ch, CURLOPT_NOBODY, true);
        } else if ($method == "PUT" || $method == "BATCH" || $method == "DELETE") {
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
        }
        if (!is_null($headers) && is_array($headers)) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        }
        if (!is_null($closure)) {
            $closure($ch);
        }
        $response = curl_exec($ch);
        if ((curl_errno($ch) == 60)) {
            /* Invalid or no certificate authority found - Retrying without ssl */
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            $response = curl_exec($ch);
        }
        /* If you want to retry on failed status code */
        $retryCodes = array('401', '403', '404');
        $retries = 0;
        $retryCount = 3;
        $httpStatus = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        if (in_array($httpStatus, $retryCodes)) {
            do {
                $response = curl_exec($ch);
                $httpStatus = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            } while (in_array($httpStatus, $retryCodes) && (++$retries < $retryCount));
        }
        if (curl_errno($ch)) {
            $response = curl_error($ch);
        }
        curl_close($ch);
        return array(
            "code" => $httpStatus,
            "response" => $response
        );
    }

    static function makeRawQuery($data, $keyPrefix = "")
    {
        $query = "";
        foreach ($data as $key => $value) {
            if (is_array($value)) {
                if (strlen($keyPrefix) > 0) {
                    $keyPrefixDummy = $keyPrefix . "[" . $key . "]";
                } else {
                    $keyPrefixDummy = $key;
                }
                $query = $query . self::makeRawQuery($value, $keyPrefixDummy);
            } else {
                if (strlen($keyPrefix) > 0) {
                    $key = $keyPrefix . "[" . $key . "]";
                }
                $query .= $key . "=" . rawurlencode($value) . "&";
            }
        }
        return rtrim($query, "&");
    }

    static function prettyPrint($o)
    {
        echo "<pre>";
        print_r($o);
        echo "</pre>";
    }
}