0

Currently I am working on a project, on which I need to GET/PUT data from a web server with basic authentication on Android.

I followed the instructions of http://loopj.com/android-async-http/ but I encountered

"Caused by: java.security.cert.CertificateException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found."`

The method on the website above is to make use of HttpClient which is deprecated now. I know there is HttpURLConnection, but I cannot find a suitable tutorial for my purpose.

David Rawson
  • 20,912
  • 7
  • 88
  • 124
Xie Jihui
  • 1
  • 1
  • One of the issues with Android is that libraries can go out of date in quickly. The particular library you are using (loopj) has not been updated for more than 2 years so you might run into more trouble with it. Since you're just starting out it might be better to try one of the more up-to-date libraries like Volley or Retrofit rather than investing your time in `loopj`. Then if there is an issue with self-signed SSL certificates and so-on it will be easier to get support. – David Rawson May 18 '17 at 06:43
  • @DavidRawson Thanks, I will try Volley – Xie Jihui May 18 '17 at 06:45

1 Answers1

-1

Answer here: Http Basic Authentication in Java using HttpClient?

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;


public class HttpBasicAuth {

    public static void main(String[] args) {

        try {
            URL url = new URL ("http://ip:port/login");
            String encoding = Base64Encoder.encode ("test1:test1");

            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            connection.setRequestProperty  ("Authorization", "Basic " + encoding);
            InputStream content = (InputStream)connection.getInputStream();
            BufferedReader in   = 
                new BufferedReader (new InputStreamReader (content));
            String line;
            while ((line = in.readLine()) != null) {
                System.out.println(line);
            }
        } catch(Exception e) {
            e.printStackTrace();
        }

    }

}
Community
  • 1
  • 1
Duc Nguyen
  • 87
  • 9
  • Thanks for your reply. This solution also have the problem mentioned in the question if I replace the url with my own url. "Trust anchor for certification path not found". How to solve this. And for"String encoding = Base64Encoder.encode ("test1:test1");", can I use "String encoding = Base64.encodeToString ("test1:test1".getBytes(),0);" instead? – Xie Jihui May 18 '17 at 06:25