I\'m trying to do basic authentication to view a protected url. I want to access the protected url which looks like this:
http://api.test.com/userinfo/vid?=1
This is so silly. I hacked something together that worked for me, I hope it'll work for you too.
public class AuthRequestDialogFragment extends DialogFragment
{
@InjectView(R.id.dauth_userinput)
public EditText userinput;
@InjectView(R.id.dauth_passinput)
public EditText passinput;
@OnClick(R.id.dauth_login)
public void login(View view) {
((Callback) getTargetFragment()).login(userinput.getText().toString(), passinput.getText().toString());
this.dismiss();
}
@OnClick(R.id.dauth_cancel)
public void cancel(View view) {
((Callback) getTargetFragment()).cancel();
this.dismiss();
}
public static interface Callback
{
public void login(String username, String password);
public void cancel();
}
@Override
public void onStart() {
super.onStart();
WindowManager wm = (WindowManager) getActivity().getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
int width = display.getWidth();
int height = display.getHeight();
getDialog().getWindow().setLayout(width*2/3, height/5*2);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.dialog_authrequest, container);
ButterKnife.inject(this, view);
getDialog().setTitle("Authorization required");
return view;
}
}
And
And
public class WebViewFragment extends Fragment implements AuthRequestDialogFragment.Callback {
@Override
public void login(String username, String password) {
Log.d(this.getClass().getName(), "Login");
myWebViewClient.login(username, password);
}
@Override
public void cancel() {
Log.d(this.getClass().getName(), "Cancel");
myWebViewClient.cancel();
}
And the most important:
private class MyWebViewClient extends WebViewClient {
private WebView myView;
private HttpAuthHandler httpAuthHandler;
private String host;
private String realm;
@Override
public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
AuthRequestDialogFragment authRequestDialogFragment = new AuthRequestDialogFragment();
FragmentManager fragmentManager = ((getActivity()).getSupportFragmentManager());
authRequestDialogFragment.setTargetFragment(WebViewFragment.this, 0);
authRequestDialogFragment.show(fragmentManager, "dialog");
this.httpAuthHandler = handler;
this.myView = view;
this.host = host;
this.realm = realm;
}
public void login(String username, String password) {
httpAuthHandler.proceed(username, password);
myView = null;
httpAuthHandler = null;
host = null;
realm = null;
}
public void cancel() {
super.onReceivedHttpAuthRequest(myView, httpAuthHandler, host, realm);
myView = null;
httpAuthHandler = null;
host = null;
realm = null;
}
}
Uses dependency:
compile 'com.jakewharton:butterknife:6.0.0'