|Android| How do i connect httpsconnection to a php

I have a doubt about Android HttpsURLConnection (I never used connections between 2 computers, just simple client). The problem is I can't connect to the urlconnection.connect, for example, i tried to find the asnwer before i made this post but i always got the same answer and never worked.

My code is simple but i can't figure out how can i fix it:

    protected void onCreate(Bundle bundle) {
    super.onCreate(bundle);
    try {
        URL url= new  URL("https://example.com/api.php?uid=test1&pwd=12345");
        HttpsURLConnection urlConnection= (HttpsURLConnection) url.openConnection();
        urlConnection.setConnectTimeout(5000);
        urlConnection.setReadTimeout(5000);
        urlConnection.setDoInput(true);
        urlConnection.setDoOutput(true);
        urlConnection.connect(); // Here is where the error occurs
        int i= urlConnection.getResponseCode(); // Here is where the error occurs too
        System.err.println(i);
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Is because of https? By the way the result of the "api.php" file is always (i didn't make that file)

{"Result":1}

And i can't get that result from the file. Please help me, Thank you.

2 answers

  • answered 2018-01-15 22:48 Timothy Bomer

    Try the below code.

    Change the API variable to the base URL of your web-based API, make the requests like this.

    String myResult = Connection.Request("SubDirectory/MyFile.php", "MyData");

    Your PHP fill will get

    $_POST["Data"];
    

    to catch the data for processing. I hope this helps!

    public class Connection {
        public static String Request(String UseURL, String data) {
            String API = "http://www.example.com/API/";
            try {
                        String data = "Data=" + URLEncoder.encode(data, "UTF-8");
                        URL postURL = new URL(API + UseURL);
                        HttpURLConnection conn = (HttpURLConnection) postURL.openConnection();
                        conn.setRequestMethod("POST");
                        conn.setDoOutput(true);
                        OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
                        writer.write(data);
                        writer.flush();
                        String line;
                        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                        String retData = "";
                        while ((line = reader.readLine()) != null) {
                          retData += line;
                        }
                        writer.close();
                        reader.close();
                        return retData;
            } catch (Exception e) {
                return "Error Connecting to Server: " + e;
            }
        }
    }
    

  • answered 2018-01-15 22:48 Ahmad Budairi

    You do not give us information about the log you got while run your code. I am trying your code on my Android Studio and no error i got.

    Do you add permission for accessing internet on your AndroidManifest.xml file?

    <uses-permission android:name="android.permission.INTERNET"/>

    If no, please add above code on your Manifest.

    You run networking operation on Main thread. Just add below code before your code:

    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
                .permitAll().build();
        StrictMode.setThreadPolicy(policy);
    

    I suppose that error you got is about android.os.NetworkOnMainThreadException. So, the whole code like this:

    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
                    .permitAll().build();
            StrictMode.setThreadPolicy(policy);
            try {
                URL url= new  URL("https://kamus.nusagates.com");
                HttpsURLConnection urlConnection= (HttpsURLConnection) url.openConnection();
                urlConnection.setConnectTimeout(5000);
                urlConnection.setReadTimeout(5000);
                urlConnection.setDoInput(true);
                urlConnection.setDoOutput(true);
                urlConnection.connect(); 
                int i= urlConnection.getResponseCode(); 
                System.err.println(i);
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
    

    Besides on above code will give you response 200.