|
| 1 | +/* |
| 2 | + Android Asynchronous Http Client Sample |
| 3 | + Copyright (c) 2014 Marek Sebera <[email protected]> |
| 4 | + http://loopj.com |
| 5 | +
|
| 6 | + Licensed under the Apache License, Version 2.0 (the "License"); |
| 7 | + you may not use this file except in compliance with the License. |
| 8 | + You may obtain a copy of the License at |
| 9 | +
|
| 10 | + http://www.apache.org/licenses/LICENSE-2.0 |
| 11 | +
|
| 12 | + Unless required by applicable law or agreed to in writing, software |
| 13 | + distributed under the License is distributed on an "AS IS" BASIS, |
| 14 | + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 15 | + See the License for the specific language governing permissions and |
| 16 | + limitations under the License. |
| 17 | +*/ |
| 18 | + |
| 19 | +package com.loopj.android.http.sample; |
| 20 | + |
| 21 | +import android.app.AlertDialog; |
| 22 | +import android.content.DialogInterface; |
| 23 | +import android.util.Log; |
| 24 | +import android.view.LayoutInflater; |
| 25 | +import android.view.View; |
| 26 | +import android.widget.EditText; |
| 27 | +import android.widget.TextView; |
| 28 | +import com.fasterxml.jackson.core.JsonFactory; |
| 29 | +import com.fasterxml.jackson.databind.ObjectMapper; |
| 30 | + |
| 31 | +import com.loopj.android.http.AsyncHttpClient; |
| 32 | +import com.loopj.android.http.Base64; |
| 33 | +import com.loopj.android.http.BaseJsonHttpResponseHandler; |
| 34 | +import com.loopj.android.http.RequestHandle; |
| 35 | +import com.loopj.android.http.ResponseHandlerInterface; |
| 36 | +import com.loopj.android.http.sample.util.SampleJSON; |
| 37 | +import java.util.List; |
| 38 | +import org.apache.http.Header; |
| 39 | +import org.apache.http.HttpEntity; |
| 40 | +import org.apache.http.message.BasicHeader; |
| 41 | + |
| 42 | +/** |
| 43 | + * This sample demonstrates how to implement HTTP 401 Basic Authentication. |
| 44 | + * |
| 45 | + * @author Noor Dawod <[email protected]> |
| 46 | + */ |
| 47 | +public class Http401Auth extends GetSample { |
| 48 | + |
| 49 | + private static final String LOG_TAG = "Http401Auth"; |
| 50 | + private static final String HEADER_WWW_AUTHENTICATE = "WWW-Authenticate"; |
| 51 | + private static final String HEADER_AUTHORIZATION = "Authorization"; |
| 52 | + private static final String HEADER_REALM_PREFIX = "realm="; |
| 53 | + private static final String HEADER_BASIC = "basic"; |
| 54 | + |
| 55 | + private static final String SECRET_USERNAME = "ahc"; |
| 56 | + private static final String SECRET_PASSWORD = "LetMeIn"; |
| 57 | + |
| 58 | + private String userName; |
| 59 | + private String passWord; |
| 60 | + |
| 61 | + public void retryRequest() { |
| 62 | + // File is still smaller than remote file; send a new request. |
| 63 | + onRunButtonPressed(); |
| 64 | + } |
| 65 | + |
| 66 | + @Override |
| 67 | + public String getDefaultURL() { |
| 68 | + return "http://httpbin.org/basic-auth/" + SECRET_USERNAME + "/" + SECRET_PASSWORD; |
| 69 | + } |
| 70 | + |
| 71 | + @Override |
| 72 | + public int getSampleTitle() { |
| 73 | + return R.string.title_401_unauth; |
| 74 | + } |
| 75 | + |
| 76 | + @Override |
| 77 | + public RequestHandle executeSample(AsyncHttpClient client, String URL, Header[] headers, HttpEntity entity, ResponseHandlerInterface responseHandler) { |
| 78 | + return client.get(this, URL, headers, null, responseHandler); |
| 79 | + } |
| 80 | + |
| 81 | + @Override |
| 82 | + public Header[] getRequestHeaders() { |
| 83 | + List<Header> headers = getRequestHeadersList(); |
| 84 | + |
| 85 | + // Add authentication header. |
| 86 | + if (userName != null && passWord != null) { |
| 87 | + byte[] base64bytes = Base64.encode( |
| 88 | + (userName + ":" + passWord).getBytes(), |
| 89 | + Base64.DEFAULT |
| 90 | + ); |
| 91 | + String credentials = new String(base64bytes); |
| 92 | + headers.add(new BasicHeader(HEADER_AUTHORIZATION, HEADER_BASIC + " " + credentials)); |
| 93 | + } |
| 94 | + |
| 95 | + return headers.toArray(new Header[headers.size()]); |
| 96 | + } |
| 97 | + |
| 98 | + @Override |
| 99 | + public ResponseHandlerInterface getResponseHandler() { |
| 100 | + return new BaseJsonHttpResponseHandler<SampleJSON>() { |
| 101 | + |
| 102 | + @Override |
| 103 | + public void onStart() { |
| 104 | + clearOutputs(); |
| 105 | + } |
| 106 | + |
| 107 | + @Override |
| 108 | + public void onSuccess(int statusCode, Header[] headers, String rawJsonResponse, SampleJSON response) { |
| 109 | + debugHeaders(LOG_TAG, headers); |
| 110 | + debugStatusCode(LOG_TAG, statusCode); |
| 111 | + if (response != null) { |
| 112 | + debugResponse(LOG_TAG, rawJsonResponse); |
| 113 | + } |
| 114 | + } |
| 115 | + |
| 116 | + @Override |
| 117 | + public void onFailure(int statusCode, Header[] headers, Throwable throwable, String rawJsonData, SampleJSON errorResponse) { |
| 118 | + debugHeaders(LOG_TAG, headers); |
| 119 | + debugStatusCode(LOG_TAG, statusCode); |
| 120 | + debugThrowable(LOG_TAG, throwable); |
| 121 | + |
| 122 | + // Ask the user for credentials if required by the server. |
| 123 | + if (statusCode == 401) { |
| 124 | + String realm = "Protected Page"; |
| 125 | + String authType = null; |
| 126 | + |
| 127 | + // Cycle through the headers and look for the WWW-Authenticate header. |
| 128 | + for (Header header : headers) { |
| 129 | + String headerName = header.getName(); |
| 130 | + if (HEADER_WWW_AUTHENTICATE.equalsIgnoreCase(headerName)) { |
| 131 | + String headerValue = header.getValue().trim(); |
| 132 | + String headerValueLowerCase = headerValue.toLowerCase(); |
| 133 | + |
| 134 | + // Get the type of auth requested. |
| 135 | + int charPos = headerValueLowerCase.indexOf(' '); |
| 136 | + if(0 < charPos) { |
| 137 | + authType = headerValueLowerCase.substring(0, charPos); |
| 138 | + |
| 139 | + // The second part should begin with a "realm=" prefix. |
| 140 | + if(headerValueLowerCase.substring(1 + charPos).startsWith(HEADER_REALM_PREFIX)) { |
| 141 | + // The new realm value, including any possible wrapping quotation. |
| 142 | + realm = headerValue.substring(1 + charPos + HEADER_REALM_PREFIX.length()); |
| 143 | + |
| 144 | + // If realm starts with a quote, remove surrounding quotes. |
| 145 | + if (realm.charAt(0) == '"' || realm.charAt(0) == '\'') { |
| 146 | + realm = realm.substring(1, realm.length() - 1); |
| 147 | + } |
| 148 | + } |
| 149 | + } |
| 150 | + } |
| 151 | + } |
| 152 | + |
| 153 | + // We will support basic auth in this sample. |
| 154 | + if (authType != null && HEADER_BASIC.equals(authType)) { |
| 155 | + // Show a dialog for the user and request user/pass. |
| 156 | + Log.d(LOG_TAG, "realm=" + realm); |
| 157 | + |
| 158 | + // Present the dialog. |
| 159 | + postRunnable(new DialogRunnable(realm)); |
| 160 | + } |
| 161 | + } |
| 162 | + } |
| 163 | + |
| 164 | + @Override |
| 165 | + protected SampleJSON parseResponse(String rawJsonData, boolean isFailure) throws Throwable { |
| 166 | + return new ObjectMapper().readValues(new JsonFactory().createParser(rawJsonData), SampleJSON.class).next(); |
| 167 | + } |
| 168 | + }; |
| 169 | + } |
| 170 | + |
| 171 | + private class DialogRunnable implements Runnable, DialogInterface.OnClickListener { |
| 172 | + |
| 173 | + final String realm; |
| 174 | + final View dialogView; |
| 175 | + |
| 176 | + public DialogRunnable(String realm) { |
| 177 | + this.realm = realm; |
| 178 | + this.dialogView = LayoutInflater.from(Http401Auth.this).inflate(R.layout.credentials, null); |
| 179 | + |
| 180 | + // Update the preface text with correct credentials. |
| 181 | + TextView preface = (TextView)dialogView.findViewById(R.id.label_credentials); |
| 182 | + String prefaceText = preface.getText().toString(); |
| 183 | + |
| 184 | + // Substitute placeholders, and re-set the value. |
| 185 | + preface.setText(String.format(prefaceText, SECRET_USERNAME, SECRET_PASSWORD)); |
| 186 | + } |
| 187 | + |
| 188 | + @Override |
| 189 | + public void run() { |
| 190 | + AlertDialog.Builder builder = new AlertDialog.Builder(Http401Auth.this); |
| 191 | + builder.setTitle(realm); |
| 192 | + builder.setView(dialogView); |
| 193 | + builder.setPositiveButton(android.R.string.ok, this); |
| 194 | + builder.setNegativeButton(android.R.string.cancel, this); |
| 195 | + builder.show(); |
| 196 | + } |
| 197 | + |
| 198 | + @Override |
| 199 | + public void onClick(DialogInterface dialog, int which) { |
| 200 | + switch (which) { |
| 201 | + case DialogInterface.BUTTON_POSITIVE: |
| 202 | + // Dismiss the dialog. |
| 203 | + dialog.dismiss(); |
| 204 | + |
| 205 | + // Update the username and password variables. |
| 206 | + userName = ((EditText) dialogView.findViewById(R.id.field_username)).getText().toString(); |
| 207 | + passWord = ((EditText) dialogView.findViewById(R.id.field_password)).getText().toString(); |
| 208 | + |
| 209 | + // Refetch the remote file. |
| 210 | + retryRequest(); |
| 211 | + |
| 212 | + break; |
| 213 | + |
| 214 | + case DialogInterface.BUTTON_NEGATIVE: |
| 215 | + // Dismiss the dialog. |
| 216 | + dialog.dismiss(); |
| 217 | + |
| 218 | + break; |
| 219 | + } |
| 220 | + } |
| 221 | + } |
| 222 | +} |
0 commit comments