https://everleaf.blogspot.com/search/label/PHP

10/17/2020

Java class simple http request GET POST PUT

Simple java http request GET POST PUT class, accept set custom header get response code, uri, header, body.Code java ini membutuhkan java class TrustedDomain.java.

code java class Request.java :


import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.net.HttpCookie;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.Proxy;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Map;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Pattern;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import TrustedDomain;

/**
 *
 * @author everleaf.blogspot.com
 */
public class Request extends Thread {

    private HttpURLConnection request;
    private OutputStream requestoutputstream;
    private OutputStreamWriter requestoutputstreamwriter;
    private PrintWriter requestwriter;
    private InputStream requestgetstream;
    private final String boundary = "===" + System.currentTimeMillis() + "===";
    private final String linefeed = "\r\n";
    private String contenttype = "text/html";
    private Proxy proxyset;
    private boolean isproxy = false;
    private int RESPONSE_CODE = 0;
    private String RESPONSE_URI = "";
    private String RESPONSE_HEADER = "";
    private String RESPONSE_COOKIE = "";
    private String RESPONSE_CONTENT = "";
    private String POSTDATAUPLOAD = "";
    private int MAX_REDIRECT = 10;

    public Request() {

    }
    
    public boolean setmaxredirect(int maxredirect){
        this.MAX_REDIRECT = maxredirect;
        return true;
    }

    public boolean setssl() {
        HostnameVerifier allHostsValid;
        try {
            allHostsValid = TrustedDomain.TrustMe();
            HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
        } catch (NoSuchAlgorithmException | KeyManagementException ex) {
            //Logger.getLogger(Request.class.getName()).log(Level.SEVERE, null, ex);
        }
        return true;
    }

    public boolean set(String action) {
        switch (action) {
            case "POST":
                this.request.setDoOutput(true);
                this.request.setDoInput(true);
                break;
            case "GET":
                this.request.setDoInput(true);
                break;
            case "PUT":
                this.request.setDoOutput(true);
                try {
                    this.request.setRequestMethod(action);
                } catch (ProtocolException ex) {
                    //Logger.getLogger(Request.class.getName()).log(Level.SEVERE, null, ex);
                }
                break;

            default:
                break;
        }
        return true;
    }

    public boolean setconnectiontimeout(int timeout) {
        this.request.setConnectTimeout(timeout);
        this.request.setReadTimeout(timeout);
        return true;
    }

    public boolean setheader(String header) {
        if (header.contains("&")) {
            String[] ampersand = header.split("&");
            for (String amp : ampersand) {
                if (amp.isEmpty() == false) {
                    String[] singleequal = amp.split("->");
                    if ((singleequal[0].equals("Content-Type")) || (singleequal[0].equals("content-type")) || (singleequal[0].equals("Content-type"))) {
                        if ((singleequal[1].contains("form-data"))) {
                            singleequal[1] = "multipart/form-data; boundary=" + this.boundary;
                            this.contenttype = "form-data";
                        } else {
                            this.contenttype = singleequal[1];
                        }
                    }
                    try {
                        this.request.addRequestProperty(singleequal[0], singleequal[1]);
                    } catch (java.lang.ArrayIndexOutOfBoundsException ex) {
                    }
                }
            }
        } else {
            String[] singleequal = header.split("->");
            if ((singleequal[0].equals("Content-Type")) || (singleequal[0].equals("content-type")) || (singleequal[0].equals("Content-type"))) {
                if ((singleequal[1].contains("form-data"))) {
                    singleequal[1] = "multipart/form-data; boundary=" + this.boundary;
                    this.contenttype = "form-data";
                } else {
                    this.contenttype = singleequal[1];
                }
            }
            try {
                this.request.addRequestProperty(singleequal[0], singleequal[1]);
            } catch (java.lang.ArrayIndexOutOfBoundsException ex) {

            }
        }
        return true;
    }

    public boolean setcookieBAK(String cookie) {
        if (cookie.contains("&")) {
            String[] ampersand = cookie.split("&");
            for (String sng : ampersand) {
                if (sng.isEmpty() == false) {
                    String[] singleequal = sng.split("->");
                    try {
                        this.request.addRequestProperty(singleequal[0], singleequal[1]);
                    } catch (java.lang.ArrayIndexOutOfBoundsException ex) {

                    }
                }
            }
        } else {
            String[] singleequal = cookie.split("->");
            try {
                this.request.addRequestProperty(singleequal[0], singleequal[1]);
            } catch (java.lang.ArrayIndexOutOfBoundsException ex) {

            }
        }
        return true;
    }

    public boolean setcookie(String cookie) {
        final String cookiey = cookie.replaceAll("(\\s+\\;?|\\;)$", "");
        final String cookieyx = cookiey.replaceAll("\\;\\;\\;\\;?|\\;\\;\\;?|\\;\\;", cookiey);
        this.request.addRequestProperty("Cookie", cookieyx);
        return true;
    }

    public boolean setpostdata(String postdata, boolean isurlencode) {
        if (this.contenttype.contains("text/plain")) {
            this.setpostdata_xwwwform(postdata, isurlencode);
        } else {
            if (this.contenttype.contains("application/x-www-form-urlencoded")) {
                this.setpostdata_xwwwform(postdata, isurlencode);
            } else {
                if (this.contenttype.contains("application/json")) {
                    this.setpostdata_json(postdata);
                } else {
                    if (this.contenttype.contains("form-data")) {
                        this.setpostdata_formdata(postdata, isurlencode);
                    }
                }
            }
        }
        return true;
    }

    public boolean setpostdata_xwwwform(String postdata, boolean isurlencode) {
        if (isurlencode) {
            String newpostdata = "";
            if (postdata.contains("&")) {
                String[] ampersand = postdata.split("&");
                for (String amp : ampersand) {
                    String[] singleequal = amp.split("->");
                    for (int t = 0; t < singleequal.length; t++) {
                        if (singleequal[t].isEmpty() == false) {
                            if (singleequal[t].isEmpty() == false) {
                                try {
                                    singleequal[t] = URLEncoder.encode(singleequal[t], "UTF-8");
                                } catch (UnsupportedEncodingException ex) {
                                    //Logger.getLogger(Request.class.getName()).log(Level.SEVERE, null, ex);
                                }
                            }
                        }
                    }
                    try {
                        newpostdata += singleequal[0] + "=" + singleequal[1] + "&";
                    } catch (java.lang.ArrayIndexOutOfBoundsException ex) {
                        newpostdata += singleequal[0] + "=&";
                    }
                }
            } else {
                String[] singleequal = postdata.split("->");
                for (int t = 0; t < singleequal.length; t++) {
                    if (singleequal[t].isEmpty() == false) {
                        try {
                            singleequal[t] = URLEncoder.encode(singleequal[t], "UTF-8");
                        } catch (UnsupportedEncodingException ex) {
                            //Logger.getLogger(Request.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                }
                try {
                    newpostdata += singleequal[0] + "=" + singleequal[1] + "&";
                } catch (java.lang.ArrayIndexOutOfBoundsException ex) {
                    newpostdata += singleequal[0] + "=&";
                }
            }
            postdata = newpostdata.replaceAll("\\&$", "");
        } else {
            String newpostdata = postdata.replaceAll("\\-\\>", "=");
            postdata = newpostdata.replaceAll("\\&$", "");
        }
        byte[] data = postdata.getBytes(StandardCharsets.UTF_8);
        int content_length = data.length;
        this.request.setRequestProperty("Content-Length", Integer.toString(content_length));
        try {
            this.requestoutputstream = this.request.getOutputStream();
            this.requestoutputstream.write(data);
            this.requestoutputstream.flush();
            this.requestoutputstream.close();
        } catch (java.net.ConnectException ex) {
        } catch (javax.net.ssl.SSLHandshakeException ex) {
        } catch (IOException ex) {
            //Logger.getLogger(Request.class.getName()).log(Level.SEVERE, null, ex);
        }
        return true;
    }

    public boolean setpostdata_json(String postdata) {
        try {
            this.requestoutputstream = request.getOutputStream();
            byte[] json = postdata.getBytes("utf-8");
            this.requestoutputstream.write(json, 0, json.length);
            this.requestoutputstream.flush();
            this.requestoutputstream.close();
        } catch (IOException ex) {
            //Logger.getLogger(Request.class.getName()).log(Level.SEVERE, null, ex);
        }
        return true;
    }

    public boolean setpostdata_formdata(String postdata, boolean isurlencode) {
        try {
            this.requestoutputstream = request.getOutputStream();
            this.requestwriter = new PrintWriter(new OutputStreamWriter(this.requestoutputstream, "UTF-8"), true);
            if (postdata.contains("&")) {
                String[] ampersand = postdata.split("&");
                for (String amp : ampersand) {
                    String[] singleequal = amp.split("->");
                    if (isurlencode) {
                        for (int t = 0; t < singleequal.length; t++) {
                            if (singleequal[t].isEmpty() == false) {
                                singleequal[t] = URLEncoder.encode(singleequal[t], "UTF-8");
                            }
                        }
                    }
                    this.requestwriter.append("--" + this.boundary).append(this.linefeed);
                    this.requestwriter.append("Content-Disposition: form-data; name=\"" + singleequal[0] + "\"").append(this.linefeed);
                    this.requestwriter.append("Content-Type: text/plain; charset=UTF-8").append(this.linefeed);
                    this.requestwriter.append(this.linefeed);
                    try {
                        if (this.contenttype.equals("application/json")) {
                            this.requestwriter.append("{" + singleequal[1] + "}").append(this.linefeed);
                        } else {
                            this.requestwriter.append(singleequal[1]).append(this.linefeed);
                        }
                    } catch (java.lang.ArrayIndexOutOfBoundsException ex) {
                        if (this.contenttype.equals("application/json")) {
                            this.requestwriter.append("{}").append(this.linefeed);
                        } else {
                            this.requestwriter.append("").append(this.linefeed);
                        }
                    }
                }
            } else {
                String[] singleequal = postdata.split("->");
                if (isurlencode) {
                    for (int t = 0; t < singleequal.length; t++) {
                        if (singleequal[t].isEmpty() == false) {
                            singleequal[t] = URLEncoder.encode(singleequal[t], "UTF-8");
                        }
                    }
                }
                this.requestwriter.append("--" + this.boundary).append(this.linefeed);
                this.requestwriter.append("Content-Disposition: form-data; name=\"" + singleequal[0] + "\"").append(this.linefeed);
                this.requestwriter.append("Content-Type: text/plain; charset=UTF-8").append(this.linefeed);
                this.requestwriter.append(this.linefeed);
                try {
                    if (this.contenttype.equals("application/json")) {
                        this.requestwriter.append("{" + singleequal[1] + "}");
                    } else {
                        this.requestwriter.append(singleequal[1]).append(this.linefeed);
                    }
                } catch (java.lang.ArrayIndexOutOfBoundsException ex) {
                    if (this.contenttype.equals("application/json")) {
                        this.requestwriter.append("{}");
                    } else {
                        this.requestwriter.append("").append(this.linefeed);
                    }
                }
            }
            this.requestwriter.flush();
        } catch (IOException ex) {
            //Logger.getLogger(Request.class.getName()).log(Level.SEVERE, null, ex);
        }
        return true;
    }

    public boolean setputdata(String rawputdata) {
        try {
            this.requestoutputstreamwriter = new OutputStreamWriter(this.request.getOutputStream());
            this.requestoutputstreamwriter.write(rawputdata);
            this.requestoutputstreamwriter.flush();
            this.requestoutputstreamwriter.close();
        } catch (Exception ex) {
            //Logger.getLogger(Request.class.getName()).log(Level.SEVERE, null, ex);
        }
        return true;
    }

    public boolean setpostdatauploadfile(String postdata) {
        try {
            this.requestoutputstream = request.getOutputStream();
            this.requestwriter = new PrintWriter(new OutputStreamWriter(this.requestoutputstream, "UTF-8"), true);
            this.requestwriter.append("--" + this.boundary).append(this.linefeed);
            if (postdata.contains("&")) {
                String[] ampersand = postdata.split("&");
                for (String amp : ampersand) {
                    String[] singleequal = amp.split("->");
                    try {
                        this.requestwriter.append("Content-Disposition: form-data; name=\"" + singleequal[0] + "\"").append(this.linefeed);
                        this.requestwriter.append("Content-Type: text/plain; charset=UTF-8").append(this.linefeed);
                        this.requestwriter.append(this.linefeed);
                        this.requestwriter.append(singleequal[1]).append(this.linefeed);
                    } catch (java.lang.ArrayIndexOutOfBoundsException ex) {
                        this.requestwriter.append("Content-Disposition: form-data; name=\"" + singleequal[0] + "\"").append(this.linefeed);
                        this.requestwriter.append("Content-Type: text/plain; charset=UTF-8").append(this.linefeed);
                        this.requestwriter.append(this.linefeed);
                        this.requestwriter.append("").append(this.linefeed);
                    }
                }
            } else {
                String[] singleequal = postdata.split("->");
                try {
                    this.requestwriter.append("Content-Disposition: form-data; name=\"" + singleequal[0] + "\"").append(this.linefeed);
                    this.requestwriter.append("Content-Type: text/plain; charset=UTF-8").append(this.linefeed);
                    this.requestwriter.append(this.linefeed);
                    this.requestwriter.append(singleequal[1]).append(this.linefeed);
                } catch (java.lang.ArrayIndexOutOfBoundsException ex) {
                    this.requestwriter.append("Content-Disposition: form-data; name=\"" + singleequal[0] + "\"").append(this.linefeed);
                    this.requestwriter.append("Content-Type: text/plain; charset=UTF-8").append(this.linefeed);
                    this.requestwriter.append(this.linefeed);
                    this.requestwriter.append("").append(this.linefeed);
                }
            }
        } catch (IOException ex) {
            //Logger.getLogger(Request.class.getName()).log(Level.SEVERE, null, ex);
        }
        this.requestwriter.append(this.linefeed);
        this.requestwriter.flush();
        return true;
    }

    public boolean setuploadfile(String varname, File file, String filename) {
        String contenttypefile = URLConnection.guessContentTypeFromName(filename);
        if (contenttypefile == null) {
            contenttypefile = "text/plain";
        }
        this.requestwriter.append("--" + this.boundary).append(this.linefeed);
        this.requestwriter.append("Content-Disposition: form-data; name=\"" + varname + "\"; filename=\"" + filename + "\"").append(this.linefeed);
        this.requestwriter.append("Content-Type:" + contenttypefile).append(this.linefeed);
        this.requestwriter.append("Content-Transfer-Encoding: binary").append(this.linefeed);
        this.requestwriter.append(this.linefeed);
        this.requestwriter.flush();
        try {
            FileInputStream inputstream = new FileInputStream(file);
            byte[] buffer = new byte[4096];
            int byteread = -1;
            while ((byteread = inputstream.read(buffer)) != -1) {
                this.requestoutputstream.write(buffer, 0, byteread);
            }
            this.requestoutputstream.flush();
            inputstream.close();
            this.requestwriter.append(this.linefeed);
            this.requestwriter.append("--" + this.boundary).append(this.linefeed);
            this.requestwriter.flush();
            this.requestwriter.close();
        } catch (FileNotFoundException ex) {
            //Logger.getLogger(Request.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            //Logger.getLogger(Request.class.getName()).log(Level.SEVERE, null, ex);
        }

        return true;
    }

    public boolean setproxy(String proxy, String type) {
        if (proxy.isEmpty() == false) {
            String[] semicol = proxy.split(":");
            switch (type) {
                case "HTTP":
                    this.proxyset = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(semicol[0], Integer.parseInt(semicol[1])));
                    this.isproxy = true;
                    break;
                case "SOCKS5":
                    this.proxyset = new Proxy(Proxy.Type.SOCKS, new InetSocketAddress(semicol[0], Integer.parseInt(semicol[1])));
                    this.isproxy = true;
                    break;
            }
        }
        return true;
    }

    public boolean seturl(String url) {
        if (this.isproxy) {
            try {
                this.request = (HttpURLConnection) new URL(url).openConnection(this.proxyset);
                this.request.setInstanceFollowRedirects(true);
            } catch (MalformedURLException ex) {
                //Logger.getLogger(Request.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                //Logger.getLogger(Request.class.getName()).log(Level.SEVERE, null, ex);
            }
        } else {
            try {
                this.request = (HttpURLConnection) new URL(url).openConnection();
                this.request.setInstanceFollowRedirects(true);
            } catch (MalformedURLException ex) {
                //Logger.getLogger(Request.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                //Logger.getLogger(Request.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        return true;
    }

    private boolean getcookie() {
        this.RESPONSE_COOKIE = "";
        String headerName = null;
        for (int i = 1; (headerName = this.request.getHeaderFieldKey(i)) != null; i++) {
            if (headerName.equals("Set-cookie") || headerName.equals("Set-Cookie") || headerName.equals("set-cookie")) {
                this.RESPONSE_COOKIE += this.request.getHeaderField(i) + ";";
            } else {
            }
        }
        return true;
    }

    private boolean getheader() {
        Map<String, List<String>> map = this.request.getHeaderFields();
        for (Map.Entry<String, List<String>> entry : map.entrySet()) {
            try {
                if (!(entry.getKey().equals("Cookie")) && !(entry.getKey().equals("Set-Cookie")) && !(entry.getKey().equals("set-cookie"))) {
                    this.RESPONSE_HEADER += entry.getKey() + "->" + entry.getValue().get(0) + "&";
                }
            } catch (java.lang.NullPointerException ex) {
            }
        }
        String e = this.RESPONSE_HEADER.replaceAll("\\&$", "");
        this.RESPONSE_HEADER = e;
        return true;
    }

    private boolean getcontent() {
        this.RESPONSE_URI = this.request.getURL().toString();
        try {
            this.RESPONSE_CODE = this.request.getResponseCode();
        } catch (Exception ex) {
            this.RESPONSE_CODE = 1996;
        }
        if (this.RESPONSE_CODE == HttpURLConnection.HTTP_OK
                || this.RESPONSE_CODE == HttpURLConnection.HTTP_CONFLICT
                || this.RESPONSE_CODE == HttpURLConnection.HTTP_MOVED_TEMP
                || this.RESPONSE_CODE == HttpURLConnection.HTTP_MOVED_PERM
                || this.RESPONSE_CODE == HttpURLConnection.HTTP_SEE_OTHER
                || this.RESPONSE_CODE == HttpURLConnection.HTTP_NOT_FOUND
                || this.RESPONSE_CODE == HttpURLConnection.HTTP_FORBIDDEN
                || this.RESPONSE_CODE == HttpURLConnection.HTTP_PAYMENT_REQUIRED
                || this.RESPONSE_CODE == HttpURLConnection.HTTP_UNAVAILABLE
                || this.RESPONSE_CODE == HttpURLConnection.HTTP_UNAUTHORIZED
                || this.RESPONSE_CODE == HttpURLConnection.HTTP_NOT_ACCEPTABLE
                || this.RESPONSE_CODE == HttpURLConnection.HTTP_BAD_METHOD
                || this.RESPONSE_CODE == HttpURLConnection.HTTP_BAD_REQUEST
                || this.RESPONSE_CODE == HttpURLConnection.HTTP_INTERNAL_ERROR
                || this.RESPONSE_CODE == 500) {
            if (this.RESPONSE_CODE >= 200 && this.RESPONSE_CODE < 400) {
                try {
                    this.requestgetstream = this.request.getInputStream();
                } catch (java.net.ConnectException ex) {
                } catch (IOException ex) {
                    //Logger.getLogger(Request.class.getName()).log(Level.SEVERE, null, ex);
                }
            } else {
                this.requestgetstream = this.request.getErrorStream();
            }
            try (BufferedReader buffer = new BufferedReader(new InputStreamReader(this.requestgetstream))) {
                String line = null;
                try {
                    while ((line = buffer.readLine()) != null) {
                        this.RESPONSE_CONTENT += line;
                    }
                } catch (java.net.SocketTimeoutException ex) {
                    this.RESPONSE_CONTENT = "notfound";
                }
                buffer.close();
                this.request.disconnect();
            } catch (java.net.SocketTimeoutException ex) {
                this.RESPONSE_CONTENT = "notfound";
                //Logger.getLogger(Request.class.getName()).log(Level.SEVERE, null, ex);
            } catch (java.net.ConnectException ex) {
                this.RESPONSE_CONTENT = "notfound";
                //Logger.getLogger(Request.class.getName()).log(Level.SEVERE, null, ex);
            } catch (java.util.NoSuchElementException ex) {
                this.RESPONSE_CONTENT = "notfound";
                //Logger.getLogger(Request.class.getName()).log(Level.SEVERE, null, ex);
            } catch (javax.net.ssl.SSLHandshakeException ex) {
                this.RESPONSE_CONTENT = "notfound";
                //Logger.getLogger(Request.class.getName()).log(Level.SEVERE, null, ex);
            } catch (java.net.SocketException ex) {
                this.RESPONSE_CONTENT = "notfound";
                //Logger.getLogger(Request.class.getName()).log(Level.SEVERE, null, ex);
            } catch (java.lang.NullPointerException ex) {
                this.RESPONSE_CONTENT = "notfound";
                //Logger.getLogger(Request.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                //Logger.getLogger(Request.class.getName()).log(Level.SEVERE, null, ex);
            }
        } else {
            this.RESPONSE_CONTENT = "website not responding";
        }
        return true;
    }

    private boolean checkredirect() {
        boolean redirect = false;
        try {
            this.RESPONSE_CODE = this.request.getResponseCode();
            if (this.RESPONSE_CODE != 0) {
                if (this.RESPONSE_CODE != HttpURLConnection.HTTP_OK) {
                    if (this.RESPONSE_CODE == HttpURLConnection.HTTP_MOVED_TEMP
                            || this.RESPONSE_CODE == HttpURLConnection.HTTP_MOVED_PERM
                            || this.RESPONSE_CODE == HttpURLConnection.HTTP_SEE_OTHER) {
                        redirect = true;
                    }
                }
                if (redirect && (this.MAX_REDIRECT > 0)) {
                    int amountredirect = this.MAX_REDIRECT - 1;
                    this.MAX_REDIRECT = amountredirect;
                    this.getcookie();
                    String useragent = this.request.getRequestProperty("User-Agent");
                    String location = this.request.getHeaderField("Location").replaceAll("www\\.", "");
                    if (Pattern.compile("https\\:\\/\\/?|http\\:\\/\\/").matcher(location).find()) {
                        Request requestnew = new Request();
                        requestnew.setmaxredirect(this.MAX_REDIRECT);
                        requestnew.setssl();
                        requestnew.seturl(location);
                        requestnew.set("GET");
                        requestnew.setheader("User-Agent->" + useragent + "&Upgrade-Insecure-Requests->1");
                        requestnew.setcookie(this.RESPONSE_COOKIE);
                        List<String> resp = requestnew.get();
                        this.RESPONSE_CODE = Integer.valueOf(resp.get(0));
                        this.RESPONSE_URI = resp.get(1);
                        this.RESPONSE_HEADER = resp.get(2);
                        this.RESPONSE_COOKIE = resp.get(3);
                        this.RESPONSE_CONTENT = resp.get(4);
                    }
                } else {
                    this.RESPONSE_URI = this.request.getURL().toString();
                }
            }
        } catch (java.net.SocketTimeoutException ex) {
            this.RESPONSE_URI = "null";
        } catch (java.net.ConnectException ex) {
            this.RESPONSE_URI = "null";
        } catch (java.util.NoSuchElementException ex) {
            this.RESPONSE_URI = "null";
        } catch (javax.net.ssl.SSLHandshakeException ex) {
            this.RESPONSE_URI = "null";
        } catch (java.net.SocketException ex) {
            this.RESPONSE_URI = "null";
        } catch (java.lang.NullPointerException ex) {
            this.RESPONSE_URI = "null";
        } catch (IOException ex) {
            this.RESPONSE_URI = "null";
        }
        return true;
    }

    public List<String> get() {
        List<String> returned = new ArrayList<String>();
        this.getcookie();
        this.getheader();
        this.getcontent();
        this.checkredirect();
        returned.add(String.valueOf(this.RESPONSE_CODE));
        returned.add(this.RESPONSE_URI);
        returned.add(this.RESPONSE_HEADER);
        returned.add(this.RESPONSE_COOKIE);
        returned.add(this.RESPONSE_CONTENT);
        return returned;
    }

    public List<String> post() {
        if (this.contenttype.equals("text/plain")) {
            try {
                this.requestoutputstream.flush();
                this.requestoutputstream.close();
                this.requestwriter.append(this.linefeed).flush();
                this.requestwriter.append("--" + this.boundary + "--").append(this.linefeed);
                this.requestwriter.close();
            } catch (IOException ex) {
                //Logger.getLogger(Request.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        List<String> returned = new ArrayList<String>();
        this.getcookie();
        this.getheader();
        this.getcontent();
        this.checkredirect();
        returned.add(String.valueOf(this.RESPONSE_CODE));
        returned.add(this.RESPONSE_URI);
        returned.add(this.RESPONSE_HEADER);
        returned.add(this.RESPONSE_COOKIE);
        returned.add(this.RESPONSE_CONTENT);
        return returned;
    }

    public List<String> put() {
        List<String> returned = new ArrayList<String>();
        this.getcookie();
        this.getheader();
        this.getcontent();
        this.checkredirect();
        returned.add(String.valueOf(this.RESPONSE_CODE));
        returned.add(this.RESPONSE_URI);
        returned.add(this.RESPONSE_HEADER);
        returned.add(this.RESPONSE_COOKIE);
        returned.add(this.RESPONSE_CONTENT);
        return returned;
    }

}

Deklarasi GET Request, simpan dengan nama ExampleGetRequest.java:
import Request;

public class ExampleGetRequest{

	public static void main(String args[]){
		Request request = new Request();
        //request.setproxy("127.0.0.1:8080", "HTTP"); #jika anda ingin menggunakan proxy HTTP atau SOCKS5
		request.setmaxredirect(10);
		request.setssl();
		request.seturl("https://your-example-website.com");
		request.set("GET");
		request.setconnectiontimeout(60000); //60s = 60000mils
		request.setheader("User-Agent->Mozilla 4&Header1->1");
		request.setcookie("session1->12345&session2->6789");
		List<String> response = request.get();
		System.out.println("Response code: "+response.get(0));
		System.out.println("Response uri: "+response.get(1));
		System.out.println("Response header: "+response.get(2));
		System.out.println("Response cookie: "+response.get(3));
		System.out.println("Response body: "+response.get(4));
	}
}
hasilnya:
Response code: 200
Response uri: https://your-example-website.com/index.php
Response header: Server->apache/2.4.2&User-Agent->Mozilla 4
Response cookie: session1=12345;session2=252525
Response body: <html>....

Deklarasi POST Request, simpan dengan nama ExamplePostRequest.java:
import Request;

public class ExamplePostRequest{

	public static void main(String args[]){
		Request request = new Request();
        //request.setproxy("127.0.0.1:8080", "HTTP"); #jika anda ingin menggunakan proxy HTTP atau SOCKS5
		request.setmaxredirect(10);
		request.setssl();
		request.seturl("https://your-example-website.com/data.php");
		request.set("POST");
		request.setconnectiontimeout(60000); //60s = 60000mils
		request.setheader("User-Agent->Mozilla 4&Header1->1&Content-Type->multipart/form-data");
		request.setcookie("session1->12345&session2->6789");
		request.setpostdata("data1->123&data2->12345");
		List<String> response = request.post();
		System.out.println("Response code: "+response.get(0));
		System.out.println("Response uri: "+response.get(1));
		System.out.println("Response header: "+response.get(2));
		System.out.println("Response cookie: "+response.get(3));
		System.out.println("Response body: "+response.get(4));
	}
}
hasilnya:
Response code: 200
Response uri: https://your-example-website.com/success.php
Response header: Server->apache/2.4.2&User-Agent->Mozilla 4
Response cookie: session1=12345;session2=252525
Response body: <html>....

Deklarasi PUT Request, simpan dengan nama ExamplePutRequest.java:
import Request;

public class ExamplePutRequest{

	public static void main(String args[]){
		Request request = new Request();
        //request.setproxy("127.0.0.1:8080", "HTTP"); #jika anda ingin menggunakan proxy HTTP atau SOCKS5
		request.setmaxredirect(10);
		request.setssl();
		request.seturl("https://your-example-website.com/data.php");
		request.set("PUT");
		request.setconnectiontimeout(60000); //60s = 60000mils
		request.setheader("User-Agent->Mozilla 4&Header1->1");
		request.setcookie("session1->12345&session2->6789");
		request.setputdata("abcd12345");
		List<String> response = request.put();
		System.out.println("Response code: "+response.get(0));
		System.out.println("Response uri: "+response.get(1));
		System.out.println("Response header: "+response.get(2));
		System.out.println("Response cookie: "+response.get(3));
		System.out.println("Response body: "+response.get(4));
	}
}
hasilnya:
Response code: 200
Response uri: https://your-example-website.com/data.php
Response header: Server->apache/2.4.2&User-Agent->Mozilla 4
Response cookie: session1=12345;session2=252525
Response body: <html>....

No comments:

Post a Comment

Diharapkan berkomentar dengan sopan dan santun, terimakasih.