How to use AndroidHttpClient (API Level 8) and UsernamePasswordCredentials? - android

Currently I am using a DefaultHttpClient with ThreadSafeClientConnManager. This works fine, but I would like to replace this by using AndroidHttpClient. Unfortunately I am not able to add UsernamePasswordCredentials which is currently important for me. Can anyone provide a tip or solution?

You need to use HttpRequestInterceptor class for authentication.
Here is an example
HttpRequestInterceptor httpRequestInterceptor = new HttpRequestInterceptor() {
public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
CredentialsProvider credsProvider = (CredentialsProvider) context.getAttribute(
ClientContext.CREDS_PROVIDER);
HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
if (authState.getAuthScheme() == null) {
AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());
Credentials creds = credsProvider.getCredentials(authScope);
if (creds != null) {
authState.setAuthScheme(new BasicScheme());
authState.setCredentials(creds);
}
}
}
};

I know the question is old but for the benefit of anyone stumbling on this (like I did), you can roll the header yourself with HttpGet object. Like so :
httpGet.addHeader("Authorization", "Basic " + Base64.encode(username+":"+password));

Some enhancement to Saad Farooq's answer, the following code works for me.
final AndroidHttpClient client = AndroidHttpClient.newInstance("Android");
getRequest = new HttpGet(url);
getRequest.addHeader("Authorization", "Basic " + Base64.encodeToString(new
String(username + ":" + password).getBytes(), Base64.NO_WRAP));

Related

How can we follow/Unfollow instagram in android app?

When I use Follow/Unfollow API in instagram. I give me error like that.
Error:
{"meta":{"error_type":"OAuthPermissionsException","code":400,"error_message":"This client has not been approved to access this resource."}}
My Post method Call is here.
public static AllMessage postAction(String action, String UserID, String mAccessToken, DefaultHttpClient httpClient) {
AllMessage ReturnMessage = new AllMessage();
String url = String.format(RELATIONSHIP_URL, new Object[]{UserID, mAccessToken});
Log.v("log_tag", "FolURL " + url);
try {
HttpParams params = new BasicHttpParams();
params.setParameter("http.protocol.version", HttpVersion.HTTP_1_1);
params.setParameter("action=", action);
if (httpClient == null) {
httpClient = OpenHttpClientConnection();
}
HttpPost httpPost = new HttpPost(url);
List<NameValuePair> arrayList = new ArrayList(2);
arrayList.add(new BasicNameValuePair("action", action));
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", String.valueOf(arrayList));
UrlEncodedFormEntity ent = new UrlEncodedFormEntity(arrayList, "UTF-8");
httpPost.setEntity(ent);
String mHttpReturnedData = readInputStreamToString(httpClient.execute(httpPost).getEntity().getContent());
Log.v("log_tag", "Return " + mHttpReturnedData);
} catch (Exception e4) {
ReturnMessage.MessageType = "Unsupported Format";
ReturnMessage.MessageError = "Unsupported data format Error -1000";
ReturnMessage.ActionSucess = false;
ReturnMessage.ActionID = 0;
ReturnMessage.PrvAction = action;
}
return ReturnMessage;
}
Please help me for this code.
You need to first register your app to use the Instagram API
The link is here https://www.instagram.com/developer/endpoints/
Then you comunicate with the endpoint https://api.instagram.com/v1/tags/nofilter/media/recent?access_token=ACCESS_TOKEN
and make the proper calls.
Currently there is not an Android SDK made by them that I have heard of, but I'm pretty sure there has to be a 3rd party out there.
Hope it helps.

Android HttpClient to accept all cookies

I'm pretty new in the Android world and maybe my question is very simple..
I have an android app where I use HttpGet to connect to a server and collect data.
However the server sometimes sets some cookies that are not remembered by my code.
I found a post where its using a custom cookie policy and is accepting everything.. just what I need.But I cant implement it.As I understand my version of java httpclient is old and does not have the functions I need.
Here's my code:
try {
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(link);
get.getParams().setParameter(
ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);
HttpResponse responseGet = client.execute(get,ctx);
status_code = responseGet.getStatusLine().getStatusCode();
HttpEntity resEntityGet = responseGet.getEntity();
if (resEntityGet != null) {
http_response = EntityUtils.toString(resEntityGet);
}
}
And the code I need to implement:
CookieStore cookieStore = new BasicCookieStore();
httpclient.setCookieStore(cookieStore);
CookieSpecFactory csf = new CookieSpecFactory() {
public CookieSpec newInstance(HttpParams params) {
return new BrowserCompatSpec() {
#Override
public void validate(Cookie cookie, CookieOrigin origin)
throws MalformedCookieException {
log.debug("allow all cookies");
}
};
}
};
httpclient.getCookieSpecs().register("easy", csf);
httpclient.getParams().setParameter(
ClientPNames.COOKIE_POLICY, "easy");
All I need is to set this csf policy to my client.
However it seems that I dont have these two functions in the library : setCookieStore and getCookieSpecs().register()
What are my options to run it ?!

Android - Form based authentication

I need to upload some data on a site, using a POST request. I know to use HTTP client to execute a POST request
The problem is that in order to do this, you should authenticate first.
The site is a simple page prompting for a username and a password. I assume it stores a cookie in the browser and checks subsequent requests to see if I'm already authenticated.
But I don't have a concrete idea how to implement this on Android.
The client just gave me this:
URL to upload: http://xyz.com/?page=add
Credentials: admin/admin
Format of data:
$_POST = {
["Name"]=>string(255)
["Address"]=>string(255)
["ZIP"]=>string(50)
["City"]=>string(100)
["Phone"]=>string(50)
["Email"]=>string(50)
["Age"]=>int(11)
["Validation_Result"]=>string(255)
["Comment"]=>string(-)
}
$_FILES["Image"] = {
["name"]=>string "3D-graphics_3D_Triangles_006790_.jpg"
["type"]=>string "image/jpeg"
["tmp_name"]=>string "C:\Windows\Temp\php1362.tmp"
["error"]=>int(0)
["size"]=>int
}
And nothing else.
Could you please point me in the right direction how I would go about doing this?
How to do HTTP authentication in android?
Check out the top answer on this question. Very good explanation.
If you are doing the POST using HttpClient as the post you linked describes, you can add Basic Authentication by doing the following:
String username, password;
DefaultHttpClient client = new DefaultHttpClient();
UsernamePasswordCredentials creds = new UsernamePasswordCredentials(username, password);
client.getCredentialsProvider().setCredentials(AuthScope.ANY, creds);
HTH
I know this is a very old question, but this was the top search result I kept running into and I wanted to add another way that I managed to do this using CookieStore and HttpClient.
For my use case (Tomcat server configuration), I was hitting my base authenticated URL to get the cookie, POSTing my auth data to the form submission endpoint, and then using the cookie for subsequent calls. Here's the simplified piece of code that got it working for me:
String cookieUrl = "SOME_URL_THAT_WILL_PROVIDE_COOKIE";
String authenticateUrl = "URL_TO_POST_FORM_DATA";
String dataUrl = "AUTHENTICATED_URL_YOU_WANT_DATA_FROM";
final String userNameKey = "FORM_KEY_FOR_USERNAME";
final String userPassKey = "FORM_KEY_FOR_PASSWORD";
final String userName = "USER_NAME";
final String userPass = "USER_PASSWORD";
HttpClient client = new DefaultHttpClient();
CookieStore cookieStore = new BasicCookieStore();
HttpContext context = new BasicHttpContext();
context.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
String getUrl = cookieUrl;
HttpGet get = new HttpGet( getUrl );
HttpResponse getResponse = client.execute(get, context);
Log.d( "ConnectionTest", "GET # " + getUrl );
Log.d( "ConnectionTest", getResponse.getStatusLine().toString() );
List<NameValuePair> authDataList = new ArrayList<NameValuePair>();
authDataList.add( new NameValuePair() {
#Override
public String getName() {
return userNameKey;
}
#Override
public String getValue() {
return userName;
}
} );
authDataList.add( new NameValuePair() {
#Override
public String getName() {
return userPassKey;
}
#Override
public String getValue() {
return userPass;
}
} );
HttpEntity authEntity = new UrlEncodedFormEntity( authDataList );
String authPostUrl = authenticateUrl;
HttpPost authPost = new HttpPost( authPostUrl );
authPost.setEntity( authEntity );
HttpResponse authPostResponse = client.execute(authPost, context);
Log.d( "ConnectionTest", "POST # " + authPostUrl );
Log.d( "ConnectionTest", authPostResponse.getStatusLine().toString() );
String getUsersUrl = dataUrl;
HttpGet usersGet = new HttpGet( getUsersUrl );
HttpResponse usersGetResponse = client.execute(usersGet, context);
Log.d( "ConnectionTest", "GET # " + getUsersUrl );
Log.d( "ConnectionTest", usersGetResponse.getStatusLine().toString() );
Log.d( "ConnectionTest", EntityUtils.toString( usersGetResponse.getEntity() ) );

Android and authenticated HttpPut with JSON body

How do you do write an HttpPut request with authentication on Android?
(I'm trying to work around using HttpURLConnection, which seems to serious have bugs (at least in Android 2.2) but GET works fine. I'd like to send a JSON representation of an array, and I have correct credentials already set using PasswordAuthentication.)
First you need to have an authentication token. And then just add this line.
httpGet.setHeader("Authorization", "Bearer " + yourToken);
Here's one general solution.
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, this.CONNECT_TIMEOUT);
HttpConnectionParams.setSoTimeout(httpParameters, this.CONNECT_TIMEOUT);
DefaultHttpClient client = new DefaultHttpClient(httpParameters);
// Retrieve user credentials.
SharedPreferences settings = context.getSharedPreferences("LOGIN", 0);
String loginNameString = settings.getString("login_name", null);
String passwordString = settings.getString("password", null);
UsernamePasswordCredentials credentials =
new UsernamePasswordCredentials(loginNameString, passwordString);
AuthScope authScope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT);
client.getCredentialsProvider().setCredentials(authScope,
credentials);
HttpPut put = new HttpPut(UPLOAD_URL);
try
{
put.setEntity(new StringEntity(responseJSONArray.toString(),
SERVER_PREFERRED_ENCODING));
put.addHeader("Content-Type", "application/json");
put.addHeader("Accept", "application/json");
HttpResponse response = client.execute(put);
// 200 type response.
if (response.getStatusLine().getStatusCode() >= HttpStatus.SC_OK &&
response.getStatusLine().getStatusCode() < HttpStatus.SC_MULTIPLE_CHOICES)
{
// Handle OK response etc........
}
}
catch (Exception e)
{
}

Android: Why is HttpPost request not going through proxy?

I've set up a new Access Point on my emulator so that I can view traffic in Fiddler by following the instructions here: http://aurir.wordpress.com/2010/03/22/tutorial-getting-android-emulator-working-with-fiddler-http-proxy-tool/
This works for the browser requests from the Emulator but the HttpPost request in my application is now visible in Fiddler.
Here's the code I'm using:
private InputStream post(String url, Hashtable<String, String> postvariables) {
DefaultHttpClient httpClient = new DefaultHttpClient();
URI uri;
InputStream data = null;
try {
uri = new URI(url);
HttpPost method = new HttpPost(uri);
method.setHeader("Content-Type","application/json");
String param = new String();
Enumeration<String> e = postvariables.keys();
while(e.hasMoreElements())
{
String key = e.nextElement();
param = param + key + "=" + postvariables.get(key);
if(e.hasMoreElements()) {
param = param + "&";
}
}
Log.i("RestClient",url + param);
HttpEntity entity = new StringEntity(param);
method.setEntity(entity);
HttpResponse response = httpClient.execute(method);
data = response.getEntity().getContent();
} catch (Exception e) {
e.printStackTrace();
}
return data;
}
Any idea what I'm doing wrong?
I have never tried this explicitly, but have seen many reports that redirecting emulator traffic by changing the APN only affects the Browser. You might have better luck running the emulator instance with the option -http-proxy <proxy>. Look here, under Emulator Startup Options (Network) for more:
http://developer.android.com/guide/developing/tools/emulator.html
$0.02: We use Charles to debug web services and booting up the emulator in this fashion works for all traffic.
Hope that helps!

Categories

Resources