Showing posts with label patch data. Show all posts
Showing posts with label patch data. Show all posts

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;
    }
}