No valid credentials provided (Mechanism level: No valid credentials provided (Mechanism level: Failed to find any Kerberos tgt)) httpclient - apache-httpclient-4.x

I am trying to download pdf file from server using http client using ntlm Auth Scheme.
but I am getting below error when. The file is getting downloaded when I used wget with username and password as parameters but if I use same username and password it fails with 401 using java code. I am using httpclient 4.2.2
Authentication error: No valid credentials provided (Mechanism level: No valid credentials provided
(Mechanism level: Failed to find any Kerberos tgt))
Below is my code to download pdf using auth.
public ByteArrayOutputStream getFile1(String resourceURL) throws CRMBusinessException {
DefaultHttpClient httpclient = new DefaultHttpClient();
ByteArrayOutputStream tmpOut = null;
try {
ICRMConfigCache cache = CacheUtil.getCRMConfigCache();
String host = cache.getConfigValue(ConfigEnum.DOCUMENT_SOURCE_HOST_NAME.toString());
String user = cache.getConfigValue(ConfigEnum.HTTP_USER_NAME.toString());
String password = cache.getConfigValue(ConfigEnum.HTTP_PASSWORD.toString());
String workstation = cache.getConfigValue(ConfigEnum.CLIENT_HOST_NAME.toString());
// Prerequisites
PreCondition.checkEmptyString(resourceURL, "'resourceURL' cannot be empty or null");
PreCondition.checkEmptyString(host, ConfigEnum.DOCUMENT_SOURCE_HOST_NAME + " property is not set in database");
PreCondition.checkEmptyString(user, ConfigEnum.HTTP_USER_NAME + " property is not set in database");
PreCondition.checkEmptyString(password, ConfigEnum.HTTP_PASSWORD + " property is not set in database");
PreCondition.checkEmptyString(workstation, ConfigEnum.CLIENT_HOST_NAME + " property is not set in database");
// NTLM authentication across all hosts and ports
httpclient.getCredentialsProvider().setCredentials(
new AuthScope(host, AuthScope.ANY_PORT, AuthScope.ANY_HOST),
new NTCredentials(user, password, workstation, MY_DOMAIN));
httpclient.getAuthSchemes().register("ntlm", new NTLMSchemeFactory());
// Execute the GET request
HttpGet httpget = new HttpGet(resourceURL);
HttpResponse httpresponse = httpclient.execute(httpget);
if (httpresponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
tmpOut = new ByteArrayOutputStream();
InputStream in = httpresponse.getEntity().getContent();
byte[] buf = new byte[1024];
int len;
while (true) {
len = in.read(buf);
if (len == -1) {
break;
}
tmpOut.write(buf, 0, len);
}
tmpOut.close();
}
aLog.debug( "IntranetFileDownloaderImpl - getFile - End - " + resourceURL);
return tmpOut;
} catch (Exception e) {
aLog.error("IntranetFileDownloaderImpl - getFile - Error while downloading " + resourceURL + "[" + e.getMessage() + "]", e);
throw new CRMBusinessException(e);
} finally {
httpclient.getConnectionManager().shutdown();
}
}
Has anyone faced this kind of issue before while using httpclient?
What does "Failed to find any Kerberos tgt" mean?
Anybody has any clue on it?

Using kotlin and httpclient version 4.5.8:
val credentialsProvider = BasicCredentialsProvider().apply {
setCredentials(
AuthScope(AuthScope.ANY),
NTCredentials(user, password, null, domain))
}
val requestConfig = RequestConfig.custom().setTargetPreferredAuthSchemes(listOf(AuthSchemes.NTLM)).build()
return HttpClients.custom()
.setDefaultCredentialsProvider(credentialsProvider)
.setDefaultRequestConfig(requestConfig)
.build()

Below code worked for me with http client version 4.2.2.
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpGet httpget = new HttpGet("url");
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(AuthScope.ANY,
new NTCredentials("username", "pwd", "", "domain"));
List<String> authtypes = new ArrayList<String>();
authtypes.add(AuthPolicy.NTLM);
httpclient.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF,authtypes);
localContext.setAttribute(ClientContext.CREDS_PROVIDER, credsProvider);
HttpResponse response = httpclient.execute(httpget, localContext);
HttpEntity entity=response.getEntity();

Related

Printing ArrayList values in SpringBoot

I created an ArrayList with the json values from an Rest API.
This is the code to read the Rest API:
#RestController
public class exemploclass {
#RequestMapping(value="/vectors")
//#Scheduled(fixedRate = 5000)
public ArrayList<StateVector> getStateVectors() throws Exception {
ArrayList<StateVector> vectors = new ArrayList<>();
String url = "https://opensky-network.org/api/states/all?lamin=41.1&lomin=6.1&lamax=43.1&lomax=8.1";
//String url = "https://opensky-network.org/api/states/all?lamin=45.8389&lomin=5.9962&lamax=47.8229&lomax=10.5226";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// optional default is GET
con.setRequestMethod("GET");
//add request header
con.setRequestProperty("User-Agent", "Mozilla/5.0");
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
JSONObject myResponse = new JSONObject(response.toString());
JSONArray states = myResponse.getJSONArray("states");
System.out.println("result after Reading JSON Response");
for (int i = 0; i < states.length(); i++) {
JSONArray jsonVector = states.getJSONArray(i);
String icao24 = jsonVector.optString(0);
String callsign = jsonVector.optString(1);
String origin_country = jsonVector.optString(2);
Boolean on_ground = jsonVector.optBoolean(8);
//System.out.println("icao24: " + icao24 + "| callsign: " + callsign + "| origin_country: " + origin_country + "| on_ground: " + on_ground);
//System.out.println("\n");
StateVector sv = new StateVector(icao24, callsign, origin_country, on_ground);
vectors.add(sv);
}
System.out.println("Size of data: " + vectors.size());
return vectors;
}
}
The last line " return vectors;" returns a list with the values i parsed and returns it like this:
But i want this more "pretty", i want it to be one Array in each line, how can i achieve this?
P.S. Its on the .html page, not on console
Your return value seems a valid Json Object. If you want it more pretty so you can read it clearly then pass it through an application that makes that json pretty.
If you call your API from Postman, it will give you a pretty Json Object which will be better formatted. This will be because you have annotated your controller with #RestController so it will deliver an application/json response which Postman will know and then it will try to make it prettier.
P.S. Its on the .html page, not on console
So you hit your API from a browser. Most browsers don't expect a Json object to be returned, so they will not make it pretty. You can't force that from your Service either.
Just hit your API from Postman, it will understand it and make it pretty.

Transfer ownership of file uploaded using Google drive API

The Google Drive API is not able to transfer ownership of a file which was uploaded from the API itself.
as per the API documentation, PUT needs to be used for transferring ownership.
when I use it with the parameters required it returns existing permission back.
doesn't update it with new owner.
if i use POST & the required parameters it throws 'The remote server returned an error: (400) Bad Request.'
I was able to change the ownership for the files that were NOT uploaded via API. the same which I use for the files which are uploaded from API. the owner doesn't change.
Is it a bug or I am doing something wrong?
-EDIT-
if anyone wants details of file uploaded using API & file created via gdocs I can.
-EDIT2-
public bool UploadReportToGoogleDrive(Model model, byte[] ReportPDF_ByteArray, string ddlAddFilesFolder = "root", bool doNotify = true)
{
bool isErrorOccured = false;
try
{
SingletonLogger.Instance.Info("UploadReportToGoogleDrive - start");
FileList fileList = new FileList();
Google.Apis.Drive.v2.Data.File uploadedFile = new Google.Apis.Drive.v2.Data.File();
Permission writerPermission = new Permission();
string accessToken = GetAccessToken();
#region FIND REPORT FOLDER
string url = "https://www.googleapis.com/drive/v2/files?"
+ "access_token=" + accessToken
+ "&q=" + HttpUtility.UrlEncode("title='My Reports' and trashed=false and mimeType in 'application/vnd.google-apps.folder'")
;
// Create POST data and convert it to a byte array.
List<string> _postData = new List<string>();
string postData = string.Join("", _postData.ToArray());
try
{
WebRequest request = WebRequest.Create(url);
string responseString = GDriveHelper.GetResponse(request);
fileList = JsonConvert.DeserializeObject<FileList>(responseString);
SingletonLogger.Instance.Info("UploadReportToGoogleDrive - folder search success");
}
catch (Exception ex)
{
SingletonLogger.Instance.Error("UploadReportToGoogleDrive\\FIND REPORT FOLDER", ex);
isErrorOccured = true;
}
#endregion FIND REPORT FOLDER
if (fileList.Items.Count == 0)
{
#region CREATE REPORT FOLDER
url = "https://www.googleapis.com/drive/v2/files?" + "access_token=" + accessToken;
// Create POST data and convert it to a byte array.
_postData = new List<string>();
_postData.Add("{");
_postData.Add("\"title\": \"" + "My Reports" + "\",");
_postData.Add("\"description\": \"Uploaded with Google Drive API\",");
_postData.Add("\"parents\": [{\"id\":\"" + "root" + "\"}],");
_postData.Add("\"mimeType\": \"" + "application/vnd.google-apps.folder" + "\"");
_postData.Add("}");
postData = string.Join("", _postData.ToArray());
try
{
WebRequest request = WebRequest.Create(url);
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/json";
// Set the ContentLength property of the WebRequest.
request.ContentLength = postData.Length;//byteArray.Length;
// Set the Method property of the request to POST.
request.Method = "POST";
// Get the request stream.
Stream dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
string responseString = GDriveHelper.GetResponse(request);
Google.Apis.Drive.v2.Data.File ReportFolder = JsonConvert.DeserializeObject<Google.Apis.Drive.v2.Data.File>(responseString);
;
ddlAddFilesFolder = ReportFolder.Id;
SingletonLogger.Instance.Info("UploadReportToGoogleDrive - folder creation success");
}
catch (Exception ex)
{
SingletonLogger.Instance.Error("UploadReportToGoogleDrive\\CREATE REPORT FOLDER", ex);
isErrorOccured = true;
}
#endregion CREATE REPORT FOLDER
}
else
{
ddlAddFilesFolder = fileList.Items.FirstOrDefault().Id;
}
if (!isErrorOccured)
{
#region UPLOAD NEW FILE - STACKOVER FLOW
//Createing the MetaData to send
_postData = new List<string>();
_postData.Add("{");
_postData.Add("\"title\": \"" + "Report_" + model.id + "\",");
_postData.Add("\"description\": \"" + " report of person - " + (model.borrowerDetails.firstName + " " + model.borrowerDetails.lastName) + "\",");
_postData.Add("\"parents\": [{\"id\":\"" + ddlAddFilesFolder + "\"}],");
_postData.Add("\"extension\": \"" + "pdf" + "\",");
_postData.Add("\"appDataContents\": \"" + true + "\",");
_postData.Add("\"mimeType\": \"" + GDriveHelper.GetMimeType("Report.pdf").ToString() + "\"");
_postData.Add("}");
postData = string.Join(" ", _postData.ToArray());
byte[] MetaDataByteArray = Encoding.UTF8.GetBytes(postData);
//// creating the Data For the file
//MemoryStream target = new MemoryStream();
//myFile.InputStream.Position = 0;
//myFile.InputStream.CopyTo(target);
//byte[] FileByteArray = target.ToArray();
string boundry = "foo_bar_baz";
url = "https://www.googleapis.com/upload/drive/v2/files?uploadType=multipart" + "&access_token=" + accessToken;
WebRequest request = WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "multipart/related; boundary=\"" + boundry + "\"";
// Wrighting Meta Data
string headerJson = string.Format("--{0}\r\nContent-Type: {1}\r\n\r\n",
boundry,
"application/json; charset=UTF-8");
string headerFile = string.Format("\r\n--{0}\r\nContent-Type: {1}\r\n\r\n",
boundry,
GDriveHelper.GetMimeType("Report.pdf").ToString());
string footer = "\r\n--" + boundry + "--\r\n";
int headerLenght = headerJson.Length + headerFile.Length + footer.Length;
request.ContentLength = MetaDataByteArray.Length + ReportPDF_ByteArray.Length + headerLenght;
Stream dataStream = request.GetRequestStream();
dataStream.Write(Encoding.UTF8.GetBytes(headerJson), 0, Encoding.UTF8.GetByteCount(headerJson)); // write the MetaData ContentType
dataStream.Write(MetaDataByteArray, 0, MetaDataByteArray.Length); // write the MetaData
dataStream.Write(Encoding.UTF8.GetBytes(headerFile), 0, Encoding.UTF8.GetByteCount(headerFile)); // write the File ContentType
dataStream.Write(ReportPDF_ByteArray, 0, ReportPDF_ByteArray.Length); // write the file
// Add the end of the request. Start with a newline
dataStream.Write(Encoding.UTF8.GetBytes(footer), 0, Encoding.UTF8.GetByteCount(footer));
dataStream.Close();
try
{
WebResponse response = request.GetResponse();
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Display the content.
//Console.WriteLine(responseFromServer);
uploadedFile = JsonConvert.DeserializeObject<Google.Apis.Drive.v2.Data.File>(responseFromServer);
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();
SingletonLogger.Instance.Info("UploadReportToGoogleDrive - upload to folder success");
}
catch (Exception ex)
{
SingletonLogger.Instance.Error("UploadReportToGoogleDrive\\CREATE REPORT FOLDER", ex);
isErrorOccured = true;
//return "Exception uploading file: uploading file." + ex.Message;
}
#endregion UPLOAD NEW FILE - STACKOVER FLOW
}
if (!isErrorOccured)
{
#region MAKE ADMIN ACCOUNT OWNER OF UPLOADED FILE - COMMENTED
url = "https://www.googleapis.com/drive/v2/files/" + uploadedFile.Id
+ "/permissions/"
+ uploadedFile.Owners[0].PermissionId
+ "?access_token=" + accessToken
+ "&sendNotificationEmails=" + (doNotify ? "true" : "false")
;
WebRequest request = WebRequest.Create(url);
string role = "owner", type = "user", value = "aniketpatil87#gmail.com";
// Create POST data and convert it to a byte array.
postData = "{"
+ "\"role\":\"" + role + "\""
+ ",\"type\": \"" + type + "\""
+ ",\"value\": \"" + value + "\""
+ ",\"permissionId\":\"" + uploadedFile.Owners[0].PermissionId + "\""
+ ",\"transferOwnership\": \"" + "true" + "\""
+ "}";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/json";
// Set the ContentLength property of the WebRequest.
request.ContentLength = postData.Length;//byteArray.Length;
// Set the Method property of the request to POST.
request.Method = "POST";
// Get the request stream.
Stream dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
//TRY CATCH - IF TOKEN IS INVALID
try
{
string responseString = GDriveHelper.GetResponse(request);
SingletonLogger.Instance.Info("UploadReportToGoogleDrive - make admin account owner success");
}
catch (Exception ex)
{
SingletonLogger.Instance.Error("UploadReportToGoogleDrive\\MAKE ADMIN ACCOUNT OWNER OF UPLOADED FILE", ex);
isErrorOccured = true;
}
#endregion MAKE ADMIN ACCOUNT OWNER OF UPLOADED FILE
if (model.Officer != default(int))
{
#region ALLOW OFFICER TO ACCESS UPLOADED FILE
OldModels.MWUsers officer = usersBL.GetAll(model.Officer).FirstOrDefault();
url = "https://www.googleapis.com/drive/v2/files/" + uploadedFile.Id
+ "/permissions/"
//+ uploadedFile.Owners[0].PermissionId
+ "?access_token=" + accessToken
+ "&sendNotificationEmails=" + (doNotify ? "true" : "false")
;
request = WebRequest.Create(url);
role = "writer";
type = "user";
value = Officer.EMail;
// Create POST data and convert it to a byte array.
postData = "{"
+ "\"role\":\"" + role + "\""
+ ",\"type\": \"" + type + "\""
+ ",\"value\": \"" + value + "\""
//+ ",\"permissionId\":\"" + uploadedFile.Owners[0].PermissionId + "\""
//+ ",\"transferOwnership\": \"" + "true" + "\""
+ "}";
byteArray = Encoding.UTF8.GetBytes(postData);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/json";
// Set the ContentLength property of the WebRequest.
request.ContentLength = postData.Length;//byteArray.Length;
// Set the Method property of the request to POST.
request.Method = "POST";
// Get the request stream.
dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
//TRY CATCH - IF TOKEN IS INVALID
try
{
string responseString = GDriveHelper.GetResponse(request);
SingletonLogger.Instance.Info("UploadReportToGoogleDrive - make officer writer success");
}
catch (Exception ex)
{
SingletonLogger.Instance.Error("UploadReportToGoogleDrive\\ALLOW OFFICER TO ACCESS UPLOADED FILE", ex);
isErrorOccured = true;
}
#endregion ALLOW OFFICER TO ACCESS UPLOADED FILE
}
}
if (isErrorOccured)
{
SingletonLogger.Instance.Info("UploadReportToGoogleDrive - report upload to gdrive failed");
}
else
{
//LogHelper.CreateLogEntry(UserContext.CurrentUser.UserID, "Uploaded " + myFileList.Count + " file(s) on Google Drive.", this.HttpContext.Request);
SingletonLogger.Instance.Info("UploadReportToGoogleDrive - report upload to gdrive success");
}
}
catch (Exception ex)
{
SingletonLogger.Instance.Info("UploadReportToGoogleDrive - Outer exception", ex);
isErrorOccured = true;
}
return isErrorOccured;
}
Not sure if you've looked at the PATCH command for permissions. The PATCH command with the proper parameters lets you transfer ownership.
Link to Google Drive API documentation
It looks like you are specifying transferOwnership in the post body, when it must be specified as a URL parameter, as per the documentation.

WP8 - Scheduled Task Agent for push notifications

I'm trying to interface my app with push notifications and the backend developer choose Pusher as notifications provider.
.NET SDK is very messy, untidy and synchronous, which it does not work on WP8, so I rewrote its and it works fine now.
The question is: is a Scheduled Task required for fetch the push notifications and update the tile/toast? Or there are any best method?
I can't change push provider sadly.
You can simply send Tile and Toast push notifications to the phone and they will work even if your app is not running. You do not need background task for that.
Here is sample code that I use in a desktop application to send push notifications to a Windows Phone 8.0:
const String toastTemplate =
"<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<wp:Notification xmlns:wp=\"WPNotification\">" +
"<wp:Toast>" +
"<wp:Text1>{0}</wp:Text1>" +
"<wp:Text2>{1}</wp:Text2>" +
"<wp:Param>{2}</wp:Param>" +
"</wp:Toast>" +
"</wp:Notification>";
String message = String.Format(toastTemplate, "Test", "updated: " + DateTime.Now.ToString(), "/Pages/SyncPage.xaml");
Status = await PushNotifiactionsManager.SendNotification(cfg.PushNotificationUri, message, 2);
public static async Task<string> SendNotification(string pushNotificationUri, string message, short notificationClass)
{
String responseText;
if (message.Length > 3072)
{
responseText = String.Format("The message must be <= 3072 bytes: {0}", message);
}
else
{
HttpClient request = new HttpClient();
// Add message headers.
request.DefaultRequestHeaders.Add("X-MessageID", Guid.NewGuid().ToString());
request.DefaultRequestHeaders.Add("X-NotificationClass", notificationClass.ToString());
if (notificationClass == 1)
{
request.DefaultRequestHeaders.Add("X-WindowsPhone-Target", "token");
}
else if (notificationClass == 2)
{
request.DefaultRequestHeaders.Add("X-WindowsPhone-Target", "toast");
}
try
{
// Send the message, and wait for the response.
HttpResponseMessage response = await request.PostAsync(pushNotificationUri, new StringContent(message));
IEnumerable<string> values;
String connectionStatus = String.Empty;
if (response.Headers.TryGetValues("X-DeviceConnectionStatus", out values))
{
connectionStatus = values.First();
}
String subscriptionStatus = String.Empty;
if (response.Headers.TryGetValues("X-SubscriptionStatus", out values))
{
subscriptionStatus = values.First();
}
String notificationStatus = String.Empty;
if (response.Headers.TryGetValues("X-NotificationStatus", out values))
{
notificationStatus = values.First();
}
responseText = String.Format("{0}: {1}, {2}, {3}, {4}",
notificationClass == 1 ? "Tile" :
notificationClass == 2 ? "Toast" : "Raw",
response.StatusCode,
connectionStatus, subscriptionStatus, notificationStatus);
}
catch (WebException ex)
{
responseText = ex.Message;
}
}
return "Notification response: " + responseText;
}

badrequest error while requesting bing microsofttranslate api?

The following code returns bad request exception.Not sure what's wrong here .
string appId = "956vaQc49TdepGpsywiM+BRqfxfgOTeCr/514=";
//go to http://msdn.microsoft.com/en-us/library/ff512386.aspx to obtain AppId.
string text = "translate this";
string language = "en";
System.Uri uri = new Uri("http://api.microsofttranslator.com/v2/Http.svc/Speak?&appId=" + appId + "&text=" + text + "&language=" + language);
try
{
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.GetAsync(uri);
response.EnsureSuccessStatusCode();
Stream responseBody = await response.Content.ReadAsStreamAsync();
// meTextToSpeeach.Source = uri;
string strResponse;
using (Stream responseStream = responseBody)
{
using (StreamReader sr = new StreamReader(responseStream, System.Text.Encoding.Unicode))
{
strResponse = sr.ReadToEnd();
}
}
}
catch (Exception)
{
}
You are not encoding the parameters (appId, text, language). You should be doing "..." + WebUtility.UrlEncode(appId) + "..." ...

login to a https URL using HttpClient java

I am trying to login to an HTTPS URL using HttpClient but failed. Can I get help with my problem? this is the code that I wrote. this code is able to get the cookies part but it's not getting logged in. After logging in I need to get some data from the logged-in page.
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet("http://www.example.com");
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
System.out.println("Initial set of cookies:");
List<Cookie> cookies = httpclient.getCookieStore().getCookies();
if (cookies.isEmpty()) {
System.out.println("None");
} else {
for (int i = 0; i < cookies.size(); i++) {
System.out.println("- " + cookies.get(i).toString());
}
}
HttpPost httpost = new HttpPost("https://www.example.com/jsp/login.jsp");
List <NameValuePair> nvps = new ArrayList <NameValuePair>();
nvps.add(new BasicNameValuePair("username", "xxx"));
nvps.add(new BasicNameValuePair("password", "xxx"));
httpost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8));
response = httpclient.execute(httpost);
entity = response.getEntity();
System.out.println("Login form get: " + response.getStatusLine());
EntityUtils.consume(entity);
System.out.println("Post logon cookies:");
cookies = httpclient.getCookieStore().getCookies();
if (cookies.isEmpty()) {
System.out.println("None");
} else {
for (int i = 0; i < cookies.size(); i++) {
System.out.println("- " + cookies.get(i).toString());
}
}
You might be missing the login button and a few more name value pairs. I'm not sure what your button is called or the value that gets sent with it.
List <NameValuePair> nvps = new ArrayList <NameValuePair>();
nvps.add(new BasicNameValuePair("username", "xxx"));
nvps.add(new BasicNameValuePair("password", "xxx"));
nvps.add(new BasicNameValuePair("button", "Login"));
I would download TamperData and then go to your webpage and log in while TamperData is up. Use it to view the POST where you log in. There might be a name value pairs that's being sent that you're missing.