I am trying to do http digest authentication from an android client. Here is a curl line that connects and does the digest successfully.
curl -i --digest --user 'c#c.com:500a436e-2d5d-4a2e-be82-19651f7ea904' -v https://localhost:8080/v1/resources/debug
Here is one attempt in my android client that returns a 401.
AndroidHttpClient httpClient = AndroidHttpClient.newInstance("user agent");
String url = "http://localhost:8080/v1/resources/debug";
URL urlObj = new URL(url);
HttpHost host = new HttpHost(urlObj.getHost(), urlObj.getPort(), urlObj.getProtocol());
AuthScope scope = new AuthScope(urlObj.getHost(), urlObj.getPort());
UsernamePasswordCredentials creds = new UsernamePasswordCredentials("c#c.com", "500a436e-2d5d-4a2e-be82-19651f7ea904");
CredentialsProvider cp = new BasicCredentialsProvider();
cp.setCredentials(scope, creds);
HttpContext credContext = new BasicHttpContext();
credContext.setAttribute(ClientContext.CREDS_PROVIDER, cp);
HttpGet job = new HttpGet(url);
HttpResponse response = httpClient.execute(host,job,credContext);
StatusLine status = response.getStatusLine();
System.out.println("#### " + status.toString());
httpClient.close();
Here is a second attempt in the client, also returns a 401.
DefaultHttpClient httpclient = new DefaultHttpClient();
DefaultHttpClient httpclient2 = new DefaultHttpClient();
HttpGet httpget = new HttpGet("https://localhost:8080/v1/resources/debug");
HttpResponse response = httpclient.execute(httpget);
System.out.println(response.getStatusLine());
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
Header authHeader = response.getFirstHeader(AUTH.WWW_AUTH);
System.out.println("authHeader = " + authHeader);
DigestScheme digestScheme = new DigestScheme();
digestScheme.processChallenge(authHeader);
UsernamePasswordCredentials creds = new UsernamePasswordCredentials("c#c.com", "500a436e-2d5d-4a2e-be82-19651f7ea904
httpget.addHeader(digestScheme.authenticate(creds, httpget));
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = httpclient2.execute(httpget, responseHandler);
System.out.println("responseBody : " + responseBody);
}
Can anyone see what I'm missing to get the authentication to work? We know it's not a server problem since the curl line works great.
Related
In the use of Autodesk's AndroidSDK, the token was successfully obtained; but at Create Bucket, unexpectedly returned “nullToken scope not set. This request does not have the required privilege.”
code:
HttpPost request = new HttpPost(BASEUrl+ upload_srv);
request.addHeader("Content-Type", "application/json");
//v2 changed the param name from 'policy' to 'policyKey'
String jsonstr ="{\"bucketKey\":\""+ newBucketName + "\", \"servicesAllowed\":{}, \"policyKey\":\"temporary\"}";
HttpEntity jsonent = new StringEntity(jsonstr,HTTP.UTF_8);
request.setEntity(jsonent);
HttpClient httpclient = getNewHttpClient();
HttpContext localContext = new BasicHttpContext();
localContext.setAttribute(ClientContext.COOKIE_STORE, globalcookies);
HttpResponse response = httpclient.execute(request,localContext);
I am working with converting website into android app.
Same code work for http URL & I can Re-use same Session id.
But in https I get session expired error.
HttpPost get3 = new HttpPost(titleURL);
entity = new StringEntity("{\"jsonrpc\":\"2.0\",\"method\":\"call\",\"params\":{\"model\":\"job.order\",\"fields\":[\"job_code\",\"sale_order_id\",\"partner_id\",\"ins_postcode\",\"client_order_ref\",\"cust_po_ref_blanket\",\"engineer_id\",\"appointment\",\"state\"],\"domain\":[[\"state\",\"=\",[\"draft\",\"confirmed\",\"installed\",\"onhold\",\"reject\",\"accepted\"]]],\"context\":{\"lang\":\"en_US\",\"tz\":false,\"uid\":1,\"search_default_open_job\":1,\"bin_size\":true},\"offset\":0,\"limit\":80,\"sort\":\"\",\"session_id\":\"3dcfe71efba0403ba454cef4d390f1fb\"},\"id\":\"r105\"}");
get3.setHeader("Content-Type", "application/json");
get3.setHeader("Cookie:","session_id=3dcfe71efba0403ba454cef4d390f1fb");
get3.setEntity(entity);
trustAll();
HttpClient client = new DefaultHttpClient();
responseBody3 = client.execute(get3, responseHandler);
My logcat error,
raise SessionExpiredException(\"Session expired\")\nSessionExpiredException: Session expired\n", "type": "client_exception"}}}
Note: My login URL executes correctly.But I cannot re-use my session id for other URL`s.
any body help me?
I have done this for downloading apk file from https url, you can modify according to your requirement
STEP 1: Created an instance of DefaultHttpClient in the first Activity when connection established.
public static DefaultHttpClient httpClient;
STEP 2: For the first time connection
URL url=new URL(urlToHit);
LoginScreen.httpClient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url.toString());
HttpResponse response = LoginScreen.httpClient.execute(httppost);
xr.parse(new InputSource(url.openStream()));
STEP 3: Now for all further connections, used the same httpClient For example in the next activity:
URL url=new URL(urlToHit);
HttpPost httppost = new HttpPost(url.toString());
HttpResponse response = LoginScreen.httpClient.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream instream = null;
if (entity != null) {
instream = entity.getContent();
}
xr.parse(new InputSource(instream)); //SAX parsing
get3.setHeader("Cookie:","session_id=3dcfe71efba0403ba454cef4d390f1fb");
That should be
get3.setHeader("Cookie","session_id=3dcfe71efba0403ba454cef4d390f1fb");
Trying to send file content to server from Android application like this:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");
final InputStreamEntity reqEntity = new InputStreamEntity(
gdFileSystemDelegate.openFileInput(openFileInput(FilePath), -1);
reqEntity.setContentType("application/octet-stream");
httppost.setEntity(reqEntity);
httpClient.execute(httppost);
But its throws an exception:
cannot retry request with a non-repeatable request entity
What does it mean ? how to fix that ?
Try to set protocol param http.protocol.expect-continue to true in DefaultHttpClient:
#Override
protected HttpParams createHttpParams() {
HttpParams params = super.createHttpParams();
HttpProtocolParams.setUseExpectContinue(params, true);
return params;
}
I have struggled for quite some time to upload photo images from android to python appengine
This is what I have tried, in Android:
void apachePost() throws Exception {
File image = new File("/sdcard/image.jpg");
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://clockinapple.appspot.com/upload");
try {
MultipartEntity entity = new MultipartEntity();
entity.addPart("type", new StringBody("photo"));
entity.addPart("data", new FileBody(image));
httppost.setEntity(entity);
HttpResponse response = httpclient.execute(httppost);
Log.v(Constants.DATA, "received http response " + response);
} catch (ClientProtocolException e){
}
}
In appengine:
class UserPhoto(db.Model):
user = db.StringProperty()
blob_key = blobstore.BlobReferenceProperty()
class UploadHandler(blobstore_handlers.BlobstoreUploadHandler):
def post(self):
upload = self.get_uploads()[0]
user_photo = UserPhoto(user="test", blob_key=upload.key())
db.put(user_photo)
return user_photo.key()
My logged server error is "Apache-HttpClient/UNAVAILABLE (java 1.4)"
I assume the headers are incorrect - I have tried many variations
Some of the links are have tried:
Ika Lan's snippet
tacticalnuclearstrike blog
I would really appreciate any help, I don't seem to be asking the right questions atm
This is what I have that works (Changed to a HttpGet), the Android code:
void apachePost(String url, String filename) throws Exception {
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse urlResponse = httpClient.execute(httpGet);
String result = EntityUtils.toString(urlResponse.getEntity());
Uri fileUri = Uri.parse(filename); // Gets the Uri of the file in the sdcard
File file = new File(new URI(fileUri.toString())); // Extracts the file from the Uri
FileBody fileBody = new FileBody(file, "multipart/form-data");
StringBody stringBody = new StringBody("Arghhh");
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
entity.addPart("file", fileBody);
entity.addPart("string", stringBody);
HttpPost httpPost = new HttpPost(result);
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost);
response.getStatusLine();
Log.v(Constants.DATA, "received http response " + response);
Log.v(Constants.DATA, "received http entity " + entity);
}
The Appengine Code:
class GetBlobstoreUrl(BaseHandler):
def get(self):
upload_url = blobstore.create_upload_url('/upload/')
logging.debug(upload_url)
self.response.out.write(upload_url)
class UploadHandler(blobstore_handlers.BlobstoreUploadHandler):
def post(self):
upload_files = self.get_uploads('file')
text_files = self.get_uploads('string')
blob_info = upload_files[0]
user_info = "text_files"
photo = clockin.UserPhoto(blob_key=blob_info.key(), user=user_info)
photo.put()
One thing that eludes me is what happened to the "entity.addPart("string", stringBody);"
it doesnt seem part of get_uploads in the blobstore object
I am developing a hotel booking app using expedia. I need to send the following rest data to server using the httppost
http:/api.ean.com/ean-services/rs/hotel/v3/list?minorRev=[current minorRev #]
&cid=55505
&apiKey=xxx-yourOwnKey-xxx
&customerUserAgent=xxx
&customerIpAddress=xxx
&locale=en_US
¤cyCode=USD
&city=Seattle
&stateProvinceCode=WA
&countryCode=US
&supplierCacheTolerance=MED
&arrivalDate=09/04/2012
&departureDate=09/05/2012
&room1=2
&numberOfResults=1
&supplierCacheTolerance=MED_ENHANCED
String urlToSendRequest = "https://example.net";
String targetDomain = "example.net";
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpHost targetHost = new HttpHost(targetDomain, 80, "http");
HttpPost httpPost = new HttpPost(urlToSendRequest);
httpPost.addHeader("Content-Type", "application/xml");
StringEntity entity = new StringEntity("<input>test</input>", "UTF-8");
entity.setContentType("application/xml");
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(targetHost, httpPost);
Reader r = new InputStreamReader(response.getEntity().getContent());