(Apache) Einloggen über Basic Authentication

  • Antworten:5
  • OffenNicht stickyNicht beantwortet
  • Forum-Beiträge: 3

23.12.2015, 22:07:38 via Website

Ich habe eine Website, die durch eine Basic Authentication geschützt ist.
Dort soll sich jetzt meine App einloggen und die Website später auslesen.

In C# hab ich das schonmal hinbekommen:

public static string LoadHttpPageWithBasicAuthentication(string url, string username, string password)
    {
        Uri myUri = new Uri(url);
        WebRequest myWebRequest = HttpWebRequest.Create(myUri);

        HttpWebRequest myHttpWebRequest = (HttpWebRequest)myWebRequest;

        NetworkCredential myNetworkCredential = new NetworkCredential(username, password);

        CredentialCache myCredentialCache = new CredentialCache();
        myCredentialCache.Add(myUri, "Basic", myNetworkCredential);

        myHttpWebRequest.PreAuthenticate = true;
        myHttpWebRequest.Credentials = myCredentialCache;

        WebResponse myWebResponse = myWebRequest.GetResponse();

        Stream responseStream = myWebResponse.GetResponseStream();

        StreamReader myStreamReader = new StreamReader(responseStream, Encoding.Default);

        string pageContent = myStreamReader.ReadToEnd();

        responseStream.Close();

        myWebResponse.Close();

        return pageContent;
    }

Wie mache ich das im Android Studio?
Ich hab schon Ewigkeiten gegoogelt, aber keine wirkliche Lösung gefunden.

Ich hoffe ihr könnt mir helfen. Ich bin in Sachen App-Entwicklung noch nicht sehr erfahren und hab bis jetzt immer nur mit C# gearbeitet.

Danke schonmal im Voraus!
Max

Antworten
  • Forum-Beiträge: 3

24.12.2015, 10:28:49 via Website

Hab ich. Die App stürzt ab und LogCat gibt folgendes aus:

12-24 09:18:54.329 2511-2511/goldacker.maximilian.authtest E/AndroidRuntime: FATAL EXCEPTION: main
Process: goldacker.maximilian.authtest, PID: 2511
java.lang.RuntimeException: Unable to start activity ComponentInfo{goldacker.maximilian.authtest/goldacker.maximilian.authtest.MainActivity}: android.os.NetworkOnMainThreadException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1273)
at java.net.InetAddress.lookupHostByName(InetAddress.java:431)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
at java.net.InetAddress.getAllByName(InetAddress.java:215)
at com.android.okhttp.internal.Network$1.resolveInetAddresses(Network.java:29)
at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:188)
at com.android.okhttp.internal.http.RouteSelector.nextProxy(RouteSelector.java:157)
at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:100)
at com.android.okhttp.internal.http.HttpEngine.createNextConnection(HttpEngine.java:357)
at com.android.okhttp.internal.http.HttpEngine.nextConnection(HttpEngine.java:340)
at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:330)
at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:248)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:433)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:114)
at goldacker.maximilian.authtest.MainActivity.onCreate(MainActivity.java:33)
at android.app.Activity.performCreate(Activity.java:6237)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
at android.app.ActivityThread.-wrap11(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5417) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 

Ich werd daraus irgendwie nicht schlau...

Antworten
  • Forum-Beiträge: 11.184

24.12.2015, 10:40:59 via App

Du darfst keine Netzwerkoperationen im Mainthread machen.Benutze einen Thread oder einen AsyncTask.
Oder gleich eine Http lib wie Volley/Ion oder OkHttp etc..

LG Pascal //It's not a bug, it's a feature. :) ;)

Johann GoldackerLudy

Antworten
  • Forum-Beiträge: 3

26.12.2015, 01:29:08 via Website

Danke, cooler Tipp! Wieder was dazu gelernt :)

Ich hab das jetzt so umgesetzt

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

public Button button;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    TextView tv = (TextView) findViewById(R.id.textView2);
    button = (Button)findViewById(R.id.button);

    button.setOnClickListener(this);
}

Runnable connectRunnable = new Runnable() {
    @Override
    public void run() {
        Authenticator.setDefault(new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("user", "password".toCharArray());
            }
        });

        HttpURLConnection c = null;
        try {
            c = (HttpURLConnection) new URL("website").openConnection();
            c.setUseCaches(false);
            c.connect();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
};

@Override
public void onClick(View v) {
    Thread connectThread = new Thread(connectRunnable);
    connectThread.start();
}

}

Dummerweise wird immernoch eine ellenlage Fehlermeldung ausgegeben.
Keine Ahnung was ich wieder falsch gemacht habe :(

Antworten