How to do a HTTP GET request on a extension?

How can I do it with OkHttp?

You need learn okhttp @Nisarga_Adhikary :sweat_smile:

Dont worry i make simple extension code to learn together :slight_smile:

SimpleOkHttp link repo

im write use browser chrome android not an idea,so maybe need fix :sweat_smile:
and maybe need add library "okhttp.jar" is com.squareup.okhttp3 library.

regards,
kangris

4 Likes

Actually, it's easy. Still, I recommend you to look at what @Taifun said.

Here is the code which I use. With simple explanation:

 @SimpleFunction(
            description = "Website source-code")
    public void WebsiteContent(final String website) {
        AsynchUtil.runAsynchronously(new Runnable() { // Always do get request Asynchronously
            @Override
            public void run() {
                try {
                    BufferedReader readStream = new BufferedReader(
                            new InputStreamReader(
                                    new URL(website).openStream())); // Open stream and read the content from streamReader to BufferedReader
                    String readLine; // Variable which will have one line of data
                    StringBuilder data = new StringBuilder(); // The result data will be stored here
                    while ((readLine = readStream.readLine()) != null) data.append(readLine); // Read all the lines from the readStream
                    readStream.close(); // IMPORTANT close the stream

                    final String finalData = data.toString(); // Make the string final with the data variable
                    activity.runOnUiThread(new Runnable() { // Always raise events on UI thread
                        @Override
                        public void run() {
                            myEvent(finalData); // You're event with data
                        }
                    });
                } catch (IOException e) {
                    e.printStackTrace(); // Error occured
                }
            }
        });
8 Likes

what packages should i import?

Import these classes

java.io.BufferedReader
java.io.IOException
android.app.Activity
java.io.InputStreamReader
java.net.HttpURLConnection
java.net.URL
com.google.appinventor.components.runtime.util.AsynchUtil

1 Like

Although @Kumaraswamy 's approach is good but it will only work for GET requests.
But if you are looking for other options then you should do this instead:

      URL obj = new URL("https://www.google.com");
      HttpURLConnection httpConnection = (HttpURLConnection)obj.openConnection();
      httpConnection.setDoOutput(true); //if you want output
      httpConnection.setRequestMethod("POST"); //request method
      BufferedReader bufferedReader = null;
      if (httpConnection.getResponseCode() == 200) {
        bufferedReader = new BufferedReader(new InputStreamReader(httpConnection.getInputStream()));
      } else {
        bufferedReader = new BufferedReader(new InputStreamReader(httpConnection.getErrorStream()));
      } 
      StringBuilder content = new StringBuilder();
      String line;
      while ((line = bufferedReader.readLine()) != null){
        content.append(line).append("\n"); 
      }
      bufferedReader.close();
      final String con = String.valueOf(content); //post wherever you need

Learn More: https://www.geeksforgeeks.org/java-net-httpurlconnection-class-java/

6 Likes

Yes :slightly_smiling_face:

#off-topic
Btw what is difference between URLConnection and HttpURLConnection :thinking: :thinking:

1 Like

HttpUrlConnection is a child and abstract class which extends UrlConnection and is more secure.
If you want more security then use HttpsUrlConnection.

2 Likes

Will HttpURLConnection work with those urls whoch has scheme https

Yes.
But HttpsUrlConnection will not work with http urls.

1 Like

When you open a URL for connection, Java will internally instantiate the right class for the scheme. You can downcast the URLConnection object to the more concrete type appropriate for the scheme, but it isn't necessary unless you need protocol specific functionality (e.g., setting HTTP headers).

4 Likes

Can any gave me the code for making a web , requesting two header and getting responsive content in dispatcher block
I am trying rapid api extensions , so can any one give me one source code of any rapid api requester extension so that I will also begin extension developing

1 Like

What have you tried yet ? Why not use web component ?

No , I want to make extensions

Show what have you tried ?

You can use this example as help :

Request headers too , When I messaged you in telegram then you said me to learn java @oseamiya
Please also tell
@Override
Tell what @vknow360 told

Ah, Okay !

Your baserow source code also include utility.java upload by url , and that make me cunfuse because its mixing in one class extends
I want to know how to do this in one class only
I donot want to use many classes

/*
* I guess this example will help you -- Don't copy paste this , try to understand this
* I've edited this here so it may have error, so as I said, try to understand --don't copy paste--
* Codes are taken from github.com/oseamiya/baserow
* @author oseamiya
*/
@SimpleFunction
public void Post(String urls){
(new Thread(new Runnable() {
            @Override
            public void run() {
            HttpURLConnection httpURLConnection = null;
                InputStream inputStream = null;
                try {
                    URL url = new URL(urls);
                    httpURLConnection = (HttpURLConnection) url.openConnection();
                    httpURLConnection.setConnectTimeout(5000);
                    httpURLConnection.setRequestProperty("Content-Type", "application/json");
                    httpURLConnection.setDoInput(true);
                    httpURLConnection.setDoOutput(true);
                    httpURLConnection.setRequestMethod(method);
                    int responseCode = httpURLConnection.getResponseCode();
                    if (responseCode / 100 == 2) {
                        inputStream = new BufferedInputStream(httpURLConnection.getInputStream());
                        String res = convertStreamToString(inputStream);
                        if(res != null){
                            activity.runOnUiThread(new Runnable(){
                                @Override
                                 public void run(){
                                 OnSuccess(res);
                                 }
                            });
                        }
                    } else {
                        String res = convertStreamToString(httpURLConnection.getErrorStream());
                        if(res != null){
                             activity.runOnUiThread(new Runnable(){
                                @Override
                                 public void run(){
                                 OnError(res);
                                 }
                            });
                        }
                    }
                   } catch(Exception e){
                       e.printStackTrace();
                      // You can trigger OnError method here in UI thread too
                   } finally {
                    if (httpUrlConnection != null) {
                        httpUrlConnection.disconnect();
                    }
})).start();
}
@SimpleEvent
public void OnSuccess(String data){
    EventDispatcher.dispatchEvent(this, "OnSuccess", data);
}
@SimpleEvent
public void OnError(String error){
    EventDispatcher.dispatchEvent(this, "OnError", error);
}
private String convertStreamToString(InputStream is) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        try {
            int len;
            while ((len = is.read(buffer)) != -1) {
                baos.write(buffer, 0, len);
            }
            return baos.toString();

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
			if(is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            try {
                baos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

Imports can be :

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
1 Like