How to Convert This Java Into Extension

Hello Friends I Have This Java Code

package com.api;

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;


public class APIMain {
    public static void main(String[] args) throws IOException, InterruptedException {
        var url = "https://b.mathdro.id/api";
        //httprequest
        var request = HttpRequest.newBuilder().GET().uri(URI.create(url)).build();
        var client = HttpClient.newBuilder().build();
        var response = client.send(request, HttpResponse.BodyHandlers.ofString());

        System.out.println(response.statusCode());
        System.out.println(response.body());

    }

}

I Want To Convert Into Extension And I Want To Get Url From User And Show Response Using Event

You can use Appy Builder Code Editor for that.
https://editor.appybuilder.com

Ok But I Am Not Able To Understand How To Write @SimpleFunction To Get Url From User And How To Show Response Using @SimpleEvent

Can You Edit This Java Code And Add These Requirement

I don’t know about Extension Developement, you can search in Community
Also see this :point_down:

It is kotlin and not java.

3 Likes

How?

See ai2 sources of the components which uses APIs like yandex translate

There Is So Much Error Showing

I have Tried But Not Working

import android.content.Context;
import android.util.Log;
import com.google.appinventor.components.annotations.*;
import com.google.appinventor.components.runtime.*;
import com.google.appinventor.components.common.ComponentCategory;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

@DesignerComponent(version = 1,  description = "fr",
        category = ComponentCategory.EXTENSION,
        nonVisible = true,   iconName = "http://appyBuilder.com/extensions/icons/extension.png")
@SimpleObject(external = true)
public class Data extends AndroidNonvisibleComponent {
    private ComponentContainer container;
    /**
     * @param container container, component will be placed in
     */
    public Data (ComponentContainer container) {
        super(container.$form());
        this.container = container;
    }
  
    @SimpleFunction(description = "B")
  public void LoadData(String API, String ID){
      final String finalURL = API + ID;
  URL url = new URL(finalURL);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    if(connection!= null){
      try {
        final String responseContent = getResponseContent(connection);
		
       
        // Dispatch the event.
        activity.runOnUiThread(new Runnable() {
          @Override
          public void run() {
            Response(responseContent);
          }
        });

      } finally {
        connection.disconnect();
      }
    }
    
    
    
    
   
  }
 
  
  @SimpleEvent(description = "E.")
  public void Response(String responseContent) {
    EventDispatcher.dispatchEvent(this, "Response", responseContent);
  }
  
  }

A mix of both actually. Only the variables are in Kotlin.

This should be your code…

package domainExtension.domainName.extensionNameInLowercase;

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

// For App Inventor & it's clones πŸ‘½
import com.google.appinventor.components.annotations.*;
import com.google.appinventor.components.common.*;
import com.google.appinventor.components.runtime.*;

// Context isn't for App Inventor or it's clones, but where a context is needed, this will help
import android.content.Context;

@DesignerComponent(
  version = 1, // Increment with updates
  description = "Describe what your extension does",
  category = ComponentCategory.EXTENSION,
  nonVisible = true,
  iconName = "images/extension.png",
  helpUrl = "https://google.com or your URL")
@SimpleObject(external = true)
public class ExtensionFileName extends AndroidNonvisibleComponent {
  private ComponentContainer container;

  // Uses android.content.Context
  private Context context;

  public ExtensionFileName(ComponentContainer container) {
    super(container.$form());
    this.container = container;

    // Sets the application context, accessible from the extension
    this.context = container.$context();
  }

  // This is a yellow event block
  @SimpleEvent(description = "What does this block do?")
  public void OnRequestResponse(String body, int statusCode) {
    EventDispatcher.dispatchEvent(this, "OnRequestResponse", body, statusCode);
  }

  // This is a purple block that would be used inside of yellow blocks
  @SimpleFunction(description = "What does this block do?")
  public void CreateRequest(String url) throws IOException, InterruptedException {
    HttpRequest request = HttpRequest.newBuilder().GET().uri(URI.create(url)).build();
    HttpClient client = HttpClient.newBuilder().build();
    HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString());

    OnRequestResponse(response.body(), response.statusCode());
  }
}

This Is The Response

Buildfile: /projects/goldv2/appinventor-sources/appinventor/build.xml

extensions:

clean:

init:

common_CommonUtils:

init:

CommonUtils:

common_CommonVersion:

init:

CommonVersion:
     [exec] Result: 128
     [exec] Result: 128

CopyToRunLibDir:

components_AndroidRuntime:

init:

CommonConstants:
    [javac] Compiling 6 source files to /projects/goldv2/appinventor-sources/appinventor/components/build/classes/CommonConstants
    [javac] warning: [options] bootstrap class path not set in conjunction with -source 1.7
    [javac] 1 warning
    [javac] Creating empty /projects/goldv2/appinventor-sources/appinventor/components/build/classes/CommonConstants/com/google/appinventor/components/common/package-info.class
      [jar] Building jar: /projects/goldv2/appinventor-sources/appinventor/build/components/CommonConstants.jar
      [jar] Building jar: /projects/goldv2/appinventor-sources/appinventor/build/components/CommonConstants-gwt.jar

HtmlEntities:
    [mkdir] Created dir: /projects/goldv2/appinventor-sources/appinventor/components/build/classes/HtmlEntities
    [javac] Compiling 1 source file to /projects/goldv2/appinventor-sources/appinventor/components/build/classes/HtmlEntities
    [javac] warning: [options] bootstrap class path not set in conjunction with -source 1.7
    [javac] 1 warning
      [jar] Building jar: /projects/goldv2/appinventor-sources/appinventor/components/build/HtmlEntities.jar

common_CommonVersion:

init:

CommonVersion:
     [exec] Result: 128
     [exec] Result: 128

AndroidRuntime:
    [mkdir] Created dir: /projects/goldv2/appinventor-sources/appinventor/components/build/classes/AndroidRuntime
    [javac] Compiling 332 source files to /projects/goldv2/appinventor-sources/appinventor/components/build/classes/AndroidRuntime
    [javac] warning: [options] bootstrap class path not set in conjunction with -source 1.7
    [javac] /projects/goldv2/appinventor-sources/appinventor/components/src/com/appybuilder/baalveer78692/ExtensionFileName/ExtensionFileName.java:7: error: package java.net.http does not exist
    [javac] import java.net.http.HttpClient;
    [javac]                     ^
    [javac] /projects/goldv2/appinventor-sources/appinventor/components/src/com/appybuilder/baalveer78692/ExtensionFileName/ExtensionFileName.java:8: error: package java.net.http does not exist
    [javac] import java.net.http.HttpRequest;
    [javac]                     ^
    [javac] /projects/goldv2/appinventor-sources/appinventor/components/src/com/appybuilder/baalveer78692/ExtensionFileName/ExtensionFileName.java:9: error: package java.net.http does not exist
    [javac] import java.net.http.HttpResponse;
    [javac]                     ^
    [javac] /projects/goldv2/appinventor-sources/appinventor/components/src/com/appybuilder/baalveer78692/ExtensionFileName/ExtensionFileName.java:49: error: cannot find symbol
    [javac]     HttpRequest request = HttpRequest.newBuilder    [javac] /projects/goldv2/appinventor-sources/appinventor/components/src/com/appybuilder/baalveer78692/ExtensionFileName/ExtensionFileName.java:49: error: cannot find symbol
    [javac]     HttpRequest request = HttpRequest.newBuilder().GET().uri(URI.create(url)).build();
    [javac]     ^
    [javac]   symbol:   class HttpRequest
    [javac]   location: class ExtensionFileName
    [javac] /projects/goldv2/appinventor-sources/appinventor/components/src/com/appybuilder/baalveer78692/ExtensionFileName/ExtensionFileName.java:49: error: cannot find symbol
    [javac]     HttpRequest request = HttpRequest.newBuilder().GET().uri(URI.create(url)).build();
    [javac]                           ^
    [javac]   symbol:   variable HttpRequest
    [javac]   location: class ExtensionFileName
    [javac] /projects/goldv2/appinventor-sources/appinventor/components/src/com/appybuilder/baalveer78692/ExtensionFileName/ExtensionFileName.java:50: error: cannot find symbol
    [javac]     HttpClient client = HttpClient.newBuilder().build();
    [javac]     ^
    [javac]   symbol:   class HttpClient
    [javac]   location: class ExtensionFileName
    [javac] /projects/goldv2/appinventor-sources/appinventor/components/src/com/appybuilder/baalveer78692/ExtensionFileName/ExtensionFileName.java:50: error: cannot find symbol
    [javac]     HttpClient client = HttpClient.newBuilder().build();
    [javac]                         ^
    [javac]   symbol:   variable HttpClient
    [javac]   location: class ExtensionFileName
    [javac] /projects/goldv2/appinventor-sources/appinventor/components/src/com/appybuilder/baalveer78692/ExtensionFileName/ExtensionFileName.java:51: error: cannot find symbol
    [javac]     HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString());
    [javac]     ^
    [javac]   symbol:   class HttpResponse
    [javac]   location: class ExtensionFileName
    [javac] /projects/goldv2/appinventor-sources/appinventor/components/src/com/appybuilder/baalveer78692/ExtensionFileName/Extensio    [javac] Note: Some input files use or override a deprecated API.
    [javac] Note: Recompile with -Xlint:deprecation for details.
    [javac] Note: Some input files use unchecked or unsafe operations.
    [javac] Note: Recompile with    [javac] Note: Some input files use or override a deprecated API.
    [javac] Note: Recompile with -Xlint:deprecation for details.
    [javac] Note: Some input files use unchecked or unsafe operations.
    [javac] Note: Recompile with -Xlint:unchecked for details.
    [javac] 9 errors
    [javac] 1 warning

BUILD FAILED
/projects/goldv2/appinventor-sources/appinventor/build.xml:35: The following error occurred while executing this line:
/projects/goldv2/appinventor-sources/appinventor/build-common.xml:372: The following error occurred while executing this line:
/projects/goldv2/appinventor-sources/appinventor/components/build.xml:141: The following error occurred while executing this line:
/projects/goldv2/appinventor-sources/appinventor/build-common.xml:118: Compile failed; see the compiler error output for details.

Total time: 7 seconds

Thats because what you imported does not exist. I filled it in as Java, now just figure out how to fix the imports.

Now Please Give Me Some Guidance

HttpClient has been added in Java 11 and Android mainly works on Java 6.

But I Hav’t Used HttpClient

But Still Not Working

Yes but @Stormi has used it in code which you are trying to compile.
If you can wait I’ll give you code tomorrow.
Or easiest solution is to perform network request in AsynchUtil thread and dispatch response using runOnUiThread.

Ok I Will Try My Best And Wait For Your Code

1 Like

That’s because he used it in his first snippet…

package com.api;

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;


public class APIMain {
    public static void main(String[] args) throws IOException, InterruptedException {
        var url = "https://b.mathdro.id/api";
        //httprequest
        var request = HttpRequest.newBuilder().GET().uri(URI.create(url)).build();
        var client = HttpClient.newBuilder().build();
        var response = client.send(request, HttpResponse.BodyHandlers.ofString());

        System.out.println(response.statusCode());
        System.out.println(response.body());

    }

}

I didn’t change any imports besides what I added.

This should work fine:

import android.content.Context;
import android.app.Activity;
import java.io.BufferedReader;
import com.google.appinventor.components.annotations.;
import com.google.appinventor.components.runtime.
;
import com.google.appinventor.components.runtime.util.AsynchUtil;
import com.google.appinventor.components.common.ComponentCategory;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
@DesignerComponent(version = 1, description = β€œfr”,
category = ComponentCategory.EXTENSION,
nonVisible = true, iconName = β€œhttp://appyBuilder.com/extensions/icons/extension.png”)
@SimpleObject(external = true)
public class Data extends AndroidNonvisibleComponent {
public Activity activity;
public Data (ComponentContainer container) {
super(container.$form());
activity = (Activity)container.$context();
}

@SimpleFunction(description = β€œB”)
public void LoadData(String API, String ID){
final String finalURL = API + ID;
AsynchUtil.runAsynchronously(new Runnable() {
public void run() {
performRequest(finalURL);
}
});
}
public void performRequest(String url){
URL url1 = new URL(url);
HttpURLConnection connection = (HttpURLConnection) url1.openConnection();
if(connection!= null){
try {
final String responseContent = getResponseContent(connection);
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
Response(responseContent);
}
});

} finally {
connection.disconnect();
}
}
}
public String getResponseContent(HttpURLConnection httpConnection){
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();
return String.valueOf(content);
}

@SimpleEvent(description = β€œE.”)
public void Response(String responseContent) {
EventDispatcher.dispatchEvent(this, β€œResponse”, responseContent);
}
}

1 Like