HttpURLConnection Not Working

Hello Everyone, I’m trying to create an extension that uses HTTPURLCONNECTION.
I can build .aix (Extension) but when i call the function SignIn on Kodular Block Nothing Happens. Please take a look at my code and guide me if anything is wrong

package com.psapi; 
import com.google.appinventor.components.annotations.*;
import com.google.appinventor.components.runtime.*;
import com.google.appinventor.components.common.*;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.io.DataOutputStream;
import org.json.JSONArray;
import org.json.JSONObject;
import org.apache.commons.io.IOUtils;
@DesignerComponent(version = 1, 
                   description = "PS Authentication",
                   category = ComponentCategory.EXTENSION,
                   nonVisible = true,
                   iconName = "")
@SimpleObject(external = true)
public class WebApi extends AndroidNonvisibleComponent {

public WebApi(ComponentContainer container) {
        super(container.$form());
    }

    String serverURL = "";
    String APIKey = "";
    int responseCode = 0;

    // Set & Get Server URL
    @SimpleProperty(category = PropertyCategory.BEHAVIOR, description = "Set Request API Key (only for RAPIDAPI Servers)")
        @DesignerProperty(editorType = PropertyTypeConstants.PROPERTY_TYPE_STRING, defaultValue = "")
        public void RequestAPIKey(String value) {
            APIKey = value;
        }
    
    @SimpleProperty(category = PropertyCategory.BEHAVIOR, description = "Get API Key")
        public String getRequestAPIKey(){
            return APIKey;
        }

    // Set & Get Request API Key
    @SimpleProperty(category = PropertyCategory.BEHAVIOR, description = "Set Server URL")
        @DesignerProperty(editorType = PropertyTypeConstants.PROPERTY_TYPE_STRING, defaultValue = "")
        public void ServerURL(String value) {
            serverURL = value;
        }

    @SimpleProperty(category = PropertyCategory.BEHAVIOR, description = "Get Server URL")
        public String getServerURL(){
            return serverURL;
        }

    

    @SimpleFunction(description = "SignIn")
    public void SignIn(String username, String password) throws IOException {
        try{
            URL url = new URL(serverURL + "/login.php");
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            String PostData = "Username=" + username + "&Password=" + password;
            con.setRequestMethod("POST");
            con.setDoOutput(true);
            con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            con.setRequestProperty("Content-Length", Integer.toString(PostData.length()));
            con.setUseCaches(false);
            try( DataOutputStream dos = new DataOutputStream(con.getOutputStream())){
                dos.writeBytes(PostData);
            }
            responseCode = con.getResponseCode();
            InputStream responseData = con.getInputStream();
            String jsonResponse = IOUtils.toString(responseData, "UTF-8");
            JSONObject json = new JSONObject(jsonResponse);
            int StatusCode = json.getJSONObject("Response").getInt("StatusCode");
            String MsgFromServer = json.getJSONObject("Response").getString("Message");
            gotSignInResponse(responseCode, StatusCode, MsgFromServer);        
            }catch(Exception e){
               gotSignInResponse(0, 0, e.getMessage());
            }

    }

    @SimpleEvent(description = "SignIn Response")
    public void gotSignInResponse(int responseCode, int statusCode, String message) {
    EventDispatcher.dispatchEvent(this, "gotSignInResponse", responseCode, statusCode, message);
    }
}

Tru with this line,

HttpURLConnection connection = (HttpURLConnection) url.openConnection();

It’s same as i have used in my code

For sending or getting the data from the web in Android then you have to call your APIs in thread.
AFAIK, your apk will be stopped whenever you used this block.
So your code must be in thread. You can visit some open sources extension for learning about thread(if you don’t know).

And your codes also seems wrong for posting data.

It should be dos.writeBytes(postData.getBytes()) ;

#off-topic

This can be done with a little Web Post block then why you don’t do this by that instead of making am extension.
Don’t use an extension when blocks can do the job.

2 Likes

Thank You @iamwsumit

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.