Switch to desktop version  
Using JAVA to send HTTPS POST and GET requests - Printable Version

+- Ewon Technical Forum (https://techforum.ewon.biz)
+-- Forum: Development (https://techforum.ewon.biz/forum-50.html)
+--- Forum: Java (https://techforum.ewon.biz/forum-53.html)
+--- Thread: Using JAVA to send HTTPS POST and GET requests (/thread-1047.html)



Using JAVA to send HTTPS POST and GET requests - AndreasABB - 17-10-2019

Hi,

I've been working with an eWON Flexy 205 for a short amount of time now. I have an application (Java 11) which obviously needs to be refactored to Java 1.4.4. So far I've managed to adapt. However, I cannot find any usefull information about how to send HTTPS POST and HTTPS GET requests. I've been told it's possible, but so far I've had no luck.

I've read all eWON Java pdf's I could find, as well as the BASIC User Guide.

I need to be able to read the HTTPS response as well.

Kind regards,
Andreas

TL;DR:
How to send HTTPS GET and POST requests and how to read them using java?


RE: Using JAVA to send HTTPS POST and GET requests - simon - 17-10-2019

Andreas,

The only way to do is to use the REQUESTHTTPX function (in ScheduleActionManager class).
This function allows you to customize the header and the body to send and you get the response into a file.

Simon


RE: Using JAVA to send HTTPS POST and GET requests - AndreasABB - 18-10-2019

Hi Simon,

First of all, thanks for the quick reply.

Second, is there an example somewhere that I could look into or an API of some sort regarding both using RequestHttpX() and retrieving data from a HTTPS Response?

Thanks in advance, 
Kind regards,
Andreas


RE: Using JAVA to send HTTPS POST and GET requests - simon - 30-10-2019

Andreas,

The function usage is the same as in BASIC except that the RESPONSEHTTPX is not implemented in JAVA.
So, you should have a look at the BASIC manual : https://developer.ewon.biz/content/basic-1

Simon


RE: Using JAVA to send HTTPS POST and GET requests - AndreasABB - 31-10-2019

Simon,

I've tried that, but I cannot figure out how it works.

Perhaps some code of what I'm trying to do helps:
Code:
try {
            java.net.URL url = new URL(URL);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setDoOutput(true);

            connection.connect();
            //write request body with JSON
            OutputStreamWriter wr = new OutputStreamWriter(connection.getOutputStream());

            wr.write(RequestJSONAuthBody);
            wr.close();

            System.out.println(connection.getResponseCode());

            //read response body
            InputStream in = connection.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            StringBuilder result = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                result.append(line);
            }
            connection.disconnect();

            JSONParser parser = new JSONParser();

            Object o = parser.parse(result.toString());
            JSONObject data = (JSONObject) o;
            authToken = (String) data.get("authToken");
            organizationID = (Long) data.get("organizationID");

        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
This is what I have accomplished with HttpUrlConnection, obviously I cannot use it on an eWON.

Thanks in advance,
Andreas


RE: Using JAVA to send HTTPS POST and GET requests - simon - 07-11-2019

Andreas,



The equivalent should be :

Code:
int status = com.ewon.ewonitf.ScheduledActionManager.RequestHttpX("https://web.com",
"POST",
"Content-Type=application/json",
"{data:test}",
"",
"/usr/response.txt");

if (status == 0)
{
            FileConnection File = (FileConnection) Connector.open("file:////usr/response.txt");
            if (!File.exists()) {
                Utils.realTimeLog("File " + Path + " not found", 1, param_logLevel);
                return;
            }

            InputStream reader = File.openInputStream();
            String line = null;

            while ((line = Utils.readLine(reader)) != null) {

                //Read Response
            }
            reader.close();
            File.close();
}

    public static String readLine(InputStream reader) throws IOException {
        // Test whether the end of file has been reached. If so, return null.
        int readChar = reader.read();
        if (readChar == -1) {
            return null;
        }
        StringBuffer string = new StringBuffer("");
        // Read until end of file or new line
        while (readChar != -1 && readChar != '\n') {
            if (readChar != '\r') {
                string.append((char)readChar);
            }
            // Read the next character
            readChar = reader.read();
        }
        return string.toString();
    }

Hope it helps

Simon


RE: Using JAVA to send HTTPS POST and GET requests - LewisH304 - 29-11-2019

Code:
package com.journaldev.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpURLConnectionExample {

    private static final String USER_AGENT = "Mozilla/5.0";

    private static final String GET_URL = "http://localhost:9090/SpringMVCExample";

    private static final String POST_URL = "http://localhost:9090/SpringMVCExample/home";

    private static final String POST_PARAMS = "userName=Pankaj";

    public static void main(String[] args) throws IOException {

        sendGET();
        System.out.println("GET DONE");
        sendPOST();
        System.out.println("POST DONE");
    }

    private static void sendGET() throws IOException {
        URL obj = new URL(GET_URL);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        con.setRequestMethod("GET");
        con.setRequestProperty("User-Agent", USER_AGENT);
        int responseCode = con.getResponseCode();
        System.out.println("GET Response Code :: " + responseCode);
        if (responseCode == HttpURLConnection.HTTP_OK) { // success
            BufferedReader in = new BufferedReader(new InputStreamReader(
                    con.getInputStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

            // print result
            System.out.println(response.toString());
        } else {
            System.out.println("GET request not worked");
        }

    }

    private static void sendPOST() throws IOException {
        URL obj = new URL(POST_URL);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        con.setRequestMethod("POST");
        con.setRequestProperty("User-Agent", USER_AGENT);

        // For POST only - START
        con.setDoOutput(true);
        OutputStream os = con.getOutputStream();
        os.write(POST_PARAMS.getBytes());
        os.flush();
        os.close();
        // For POST only - END

        int responseCode = con.getResponseCode();
        System.out.println("POST Response Code :: " + responseCode);

        if (responseCode == HttpURLConnection.HTTP_OK) { //success
            BufferedReader in = new BufferedReader(new InputStreamReader(
                    con.getInputStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

            // print result
            System.out.println(response.toString());
        } else {
            System.out.println("POST request not worked");
        }
    }

}
Try this code! Hope they help you!
Regards,
Lewis


RE: Using JAVA to send HTTPS POST and GET requests - simon - 03-12-2019

Hi Lewis,

The java.net.HttpURLConnection class is unfortunately not supported by our JVM.
You must use the proprietary function REQUESTHTTPX.

Simon


RE: Using JAVA to send HTTPS POST and GET requests - LewisH304 - 04-04-2020

Below are the steps we need to follow for sending Java HTTP requests using HttpURLConnection class.

Create URL object from the GET/POST URL String.
Call openConnection() method on URL object that returns instance of HttpURLConnection
Set the request method in HttpURLConnection instance, default value is GET.
Call setRequestProperty() method on HttpURLConnection instance to set request header values, such as “User-Agent” and “Accept-Language” etc.
We can call getResponseCode() to get the response HTTP code. This way we know if the request was processed successfully or there was any HTTP error message thrown.
For GET, we can simply use Reader and InputStream to read the response and process it accordingly.
For POST, before we read response we need to get the OutputStream from HttpURLConnection instance and write POST parameters into it.


RE: Using JAVA to send HTTPS POST and GET requests - simon - 08-04-2020

Again, this class is NOT supported by the Ewon Flexy JVM.
Use the ScheduleActionsManager to get the proper functions to send or read data through HTTP(S)


RE: Using JAVA to send HTTPS POST and GET requests - esp70 - 07-05-2020

(08-04-2020, 08:56 PM)simon Wrote: Again, this class is NOT supported by the Ewon Flexy JVM.
Use the ScheduleActionsManager to get the proper functions to send or read data through HTTP(S)
Hey Simon-

New user here and I am trying to organize my project goals. HTTP POST/GETs are a priority to understand if there are limitations with the Flexy. 

I see you say that the HttpURLConnection is not supported by the Ewon Flexy JVM, yet it is a part of the java.net package that is included in the javaetk.jar (java 1.4).

I do not have access to an eWON Flexy at all times of development, and if you are correct, then how do I know what the JVM will run without testing each and every Java class individually within Flexy? I would think that the Flexy JVM could run every class that is within the javaetk.jar?? I am hoping that I misunderstood your answer but it sure does seem like we should be able to use all classes within the javaetk.jar that compiles to it in eclipse. 

Best Regards,
Eric


RE: Using JAVA to send HTTPS POST and GET requests - simon - 07-05-2020

Hi Eric,

I have finally tested the class by myself and it partially works.
Actually I have used an example based on https://www.journaldev.com/7148/java-httpurlconnection-example-java-http-request-get-post
I have tried to connect to an url with a name (http://mysite.com) and it returned a DNS error.
By using an IP it worked. So it seems there is a problem with the DNS resolution when using this class.
If I use an HTTPS link, it clearly states that the HTTPS is NOT implemented.

So, in short, if you want to use HTTPS and/or a name into the url, you must use the RequestHttpX() function.

  2020-05-07_19-01-41.png (Size: 35,61 KB / Downloads: 20)

See also https://hmsnetworks.blob.core.windows.net/www/docs/librariesprovider10/downloads-monitored/manuals/knowledge-base/kb-0256-00-en-get-put-https-request-using-basic-script-or-java.pdf?sfvrsn=166256d7_6

So, yes, everything that is in the javaetk.jar should be supported, but that is not always true unfortunately.
If you tell me more about the project, I may be able to tell you if it is possible and what functions to use.

Simon


RE: Using JAVA to send HTTPS POST and GET requests - esp70 - 08-05-2020

(07-05-2020, 11:59 PM)simon Wrote: Hi Eric,

I have finally tested the class by myself and it partially works.
Actually I have used an example based on https://www.journaldev.com/7148/java-httpurlconnection-example-java-http-request-get-post
I have tried to connect to an url with a name (http://mysite.com) and it returned a DNS error.
By using an IP it worked. So it seems there is a problem with the DNS resolution when using this class.
If I use an HTTPS link, it clearly states that the HTTPS is NOT implemented.

So, in short, if you want to use HTTPS and/or a name into the url, you must use the RequestHttpX() function.


See also https://hmsnetworks.blob.core.windows.net/www/docs/librariesprovider10/downloads-monitored/manuals/knowledge-base/kb-0256-00-en-get-put-https-request-using-basic-script-or-java.pdf?sfvrsn=166256d7_6

So, yes, everything that is in the javaetk.jar should be supported, but that is not always true unfortunately.
If you tell me more about the project, I may be able to tell you if it is possible and what functions to use.

Simon

Simon,

Thank you for the quick reply!
For the HTTP portion of my project, I have to make sure that we can push zipped files (hopefully the zip libraries work!!) to a HTTP server. In fact, I would like to stream the files with Multipart form data or as an Octet stream if possible.
Again, I do not have a Flexy currently to test this, I would just setup my eclipse to perform the testing on my server.

On a side note...is there any source code for javaetk that are posted? It seems like that would go a long way at understanding the system?

Regards,
Eric


RE: Using JAVA to send HTTPS POST and GET requests - simon - 11-05-2020

Hi Eric,

Yes, zipping a file should work.

I have already tested that and it worked (but it may take some time according to the size of the file to zip):
Code:
public static void main(String[] args) throws Exception  {
        
                
        System.out.println("zip starting");
    
            FileWriter fileWriter = new FileWriter("/usr/t.txt", true);
            fileWriter.write("test2");
            fileWriter.close();
            
            File f = new File("/usr/events.txt");
            
            zipFile(f, "/usr/t.zip");        
            System.out.println("zip end");
        
    }
    
       public static void zipFile(File inputFile, String zipFilePath) {
    
                       try {
        
               
           
                           // Wrap a FileOutputStream around a ZipOutputStream
                           // to store the zip stream to a file. Note that this is
                           // not absolutely necessary
                           FileOutputStream fileOutputStream = new FileOutputStream(zipFilePath);
                           ZipOutputStream zipOutputStream = new ZipOutputStream(fileOutputStream);

                           // a ZipEntry represents a file entry in the zip archive
                           // We name the ZipEntry after the original file's name
                           ZipEntry zipEntry = new ZipEntry(inputFile.getName());
                           zipOutputStream.putNextEntry(zipEntry);
                           FileInputStream fileInputStream = new FileInputStream(inputFile);
    
                           byte[] buf = new byte[(int)(inputFile.length()/2)];
                           int bytesRead;

                           // Read the input file by chucks of 1024 bytes
                           // and write the read bytes to the zip stream

                           while ((bytesRead = fileInputStream.read(buf)) > 0) {

                               zipOutputStream.write(buf, 0, bytesRead);
                           }
                           // close ZipEntry to store the stream to the file
                           zipOutputStream.closeEntry();

                           zipOutputStream.close();
                           fileOutputStream.close();

                          // System.out.println("Regular file :" + inputFile.getCanonicalPath()+" is zipped to archive :"+zipFilePath);

                       } catch (IOException e) {

                           e.printStackTrace();

                       }

                   }

Regarding the Data post, the multipart form data is what the PUTHTTP or REQUESTHTTPX functions do when you define some files to upload  (4th arg of PUTHTTP function and 5th arg of the RequesHttpX function).  You can refer to the BASIC manual for that (functions definition are very similar) https://developer.ewon.biz/system/files_force/rg-0006-01-en-basic-programming.pdf?download=1.

Simon