How to get all registered user's from xmpp server(openfire) in android - chat

Hi i need to get all registered user from xmpp server(openfire).
try {
UserSearchManager search = new UserSearchManager(connection);
Form searchForm = search.getSearchForm("search."+connection.getServiceName());
Form answerForm = searchForm.createAnswerForm();
answerForm.setAnswer("Username", true);
answerForm.setAnswer("search", "anbu");
ReportedData data = search.getSearchResults(answerForm, "search." + connection.getServiceName());
if (data.getRows() != null) {
Iterator<ReportedData.Row> it = data.getRows();
while (it.hasNext()) {
ReportedData.Row row = it.next();
Iterator iterator = row.getValues("jid");
if (iterator.hasNext()) {
String value = iterator.next().toString();
Log.i("Iteartor values......", " " + value);
}
}
}
} catch (XMPPException e2) {
e2.printStackTrace();
}
I have installed search.jar in admin panel. still i am getting (remote server not found). But chat is working for me.

And why not using the REST API plugin for Openfire?
https://www.igniterealtime.org/projects/openfire/plugins/restapi/readme.html#retrieve-users

Related

Http Post Flutter to SAP

Im trying to use http post to transfer data from flutter to SAP. I can get data without any problem, but post attempt is failing with code 403 (x-csrf-token invalid)
I had the same problem while working in C# but that was resolved using event handler, that triggers just before save (please see below extract of C# code) but i'm unable to find option in flutter. Please guide..
zZSSALE1SRVEntity.SendingRequest2 += new EventHandler<SendingRequest2EventArgs>(_container_SendingRequest_Enhance);
zZSSALE1SRVEntity.SaveChanges();
private void _container_SendingRequest_Enhance(object sender, SendingRequest2EventArgs e)
{
HttpWebResponse response;
string empty = string.Empty;
string str = string.Empty;
CookieContainer cookieContainer = new CookieContainer();
OdataSsaleDEV.ZZSSALE1_SRV_Entities zZSSALE1SRVEntity = new OdataSsaleDEV.ZZSSALE1_SRV_Entities(app_uri)
{
Credentials = credentials
};
string str1 ;
if (empty == string.Empty)
{
HttpWebRequest credentials = (HttpWebRequest)WebRequest.Create(zZSSALE1SRVEntity.BaseUri);
credentials.Method = "GET";
credentials.Headers.Add("X-CSRF-Token", "Fetch");
credentials.Credentials = zZSSALE1SRVEntity.Credentials;
cookieContainer = new CookieContainer();
credentials.CookieContainer = cookieContainer;
try
{
response = (HttpWebResponse)credentials.GetResponse();
}
catch (WebException webException)
{
MessageBox.Show(webException.Message);
return;
}
catch (Exception exception)
{
MessageBox.Show(exception.Message);
return;
}
empty = response.Headers.Get("X-CSRF-Token");
str = response.Headers.Get("Set-Cookie");
credentials.Abort();
}
if (empty != string.Empty)
{
e.RequestMessage.SetHeader("x-csrf-token", empty);
foreach (Cookie cooky in cookieContainer.GetCookies(zZSSALE1SRVEntity.BaseUri))
{
str1 = string.Concat(str1, ";", cooky.ToString());
}
e.RequestMessage.SetHeader("Cookie", str1.Substring(1));
}
Issue resolved.
Actually server requires session cookies (MYSAPSSO and SAP_SESSIONID) along with x-csrf-token.

How to attach multiple videos and photos to a status post with Facebook graph API

I'm trying to publish a post with multiple attached videos and photos via the Facebook Graph API. I uploaded the videos and photos first using a batch request and get the ids successfully for the uploaded media. Then I pass the media ids along with the post data using attached_media. Things work fine for single or multiple photos. But not for a single video or multiple videos. I got this error: "Graph returned an error: (#10) Application does not have permission for this action" whenever ids of videos are included in attached_media.
I know as a user you have the ability to attach multiple videos and photos to a Facebook post. Does the Facebook Graph API just flat out not support this for multiple videos?
I am working with C# and Unity
Here is the function that uploads videos and then sends a post with attached result videos ids:
private IEnumerator UploadMediaWithStatus(string message, string[] mediaUrls)
{
FacebookPostStatusUpdatedEvent.Invoke("Submitting FB post ... ");
var curPage = m_UserPages[FacebookFeedsList.GetInstance().ActiveFeed] as IDictionary<string, object>;
var fbClient = new FacebookClient(curPage["access_token"].ToString());
List<string> mediaIDs = new List<string> ();
foreach (string mediaUrl in mediaUrls)
{
WWW _media = new WWW("file://" + mediaUrl);
yield return _media;
if (!System.String.IsNullOrEmpty(_media.error))
{
FacebookPostStatusUpdatedEvent.Invoke("FB post failed: error loading media " + mediaUrl);
//TruLogger.LogError("cant load Image : " + _image.error);
yield break;
}
byte[] mediaData = null;
FacebookMediaObject medObj = new FacebookMediaObject();
JsonObject p = new JsonObject();
mediaData = _media.bytes;
medObj.SetValue(mediaData);
medObj.FileName = "InteractiveConsole.mp4";
medObj.ContentType = "multipart/form-data";
p.Add("description", message);
p.Add("source", medObj);
uploadedImgID = "";
fbClient.PostCompleted += OnPostImageUploadComplete;
fbClient.PostAsync("/me/videos", p);
//wait for image upload status and hopefully it returned a media ID on successful image upload
while (uploadedImgID == "")
{
//if image updload failed because of rate limit failure we can just abort rest of this
if (rateLimitErrorOccurred)
{
rateLimitErrorOccurred = false;
yield break;
}
yield return true;
}
//if video uploaded succesfully
if (uploadedImgID != null)
{
mediaIDs.Add (uploadedImgID);
var response = (JsonObject)fbClient.Get("/" + uploadedImgID + "?fields=status,published");
TruLogger.LogError("Video Status Details: " + response.ToString());
string vidStatus = (response["status"] as IDictionary<string, object>)["video_status"] as string;
while( vidStatus != "ready")
{
yield return new WaitForSeconds(5.0f);
response = (JsonObject)fbClient.Get("/" + uploadedImgID + "?fields=status,published");
TruLogger.LogError("Video Status Details: " + response.ToString());
vidStatus = (response["status"] as IDictionary<string, object>)["video_status"] as string;
}
TruLogger.LogError("Video ready");
yield return new WaitForSeconds(5.0f);
}
}
if (mediaIDs.Count > 0)
{
curPage = m_UserPages[FacebookFeedsList.GetInstance().ActiveFeed] as IDictionary<string, object>;
fbClient = new FacebookClient(curPage["access_token"].ToString());
JsonObject p = new JsonObject();
p.Add("message", message);
for (int i = 0; i < mediaIDs.Count; i++)
{
p.Add ("attached_media["+ i + "]", "{\"media_fbid\":\"" + mediaIDs[i] + "\"}");
}
fbClient.PostCompleted += OnPostUploadComplete;
fbClient.PostAsync("/me/feed", p);
}
}
void OnPostImageUploadComplete(object sender, FacebookApiEventArgs args)
{
//if successful store resulting ID of image on Facebook
try
{
var json = args.GetResultData<JsonObject>();
uploadedImgID = json["id"].ToString();
//TruLogger.LogError(json.ToString());
}
catch (Exception e)
{
apiPostStatusMessage = "FB post failed: media upload error";
TruLogger.LogError (e.Message);
TruLogger.LogError (e.InnerException.ToString());
FacebookOAuthException oEx = (FacebookOAuthException)(e.InnerException);
if (oEx != null) {
TruLogger.LogError ("Error Type: " + oEx.ErrorType);
TruLogger.LogError ("Error Code: " + oEx.ErrorCode);
TruLogger.LogError ("Error Subcode: " + oEx.ErrorSubcode);
apiAbortErrorCode = oEx.ErrorCode;
if (apiAbortErrorCode == 32 || apiAbortErrorCode == 4)
{
rateLimitErrorOccurred = true;
apiPostAbortErrorMessage = "WHOOPS! Looks like you have exceeded the daily API rate quota for one or more of your feeds. You may have to wait between 1-24 hours until Facebook replenishes your balance for these feeds: \n\n" + e.InnerException.ToString ();
}
else
{
rateLimitErrorOccurred = false;
apiPostAbortErrorMessage = "WHOOPS! Looks like your session has expired or become invalid. Try Signing in again to revalidate your session: \n\n" + e.InnerException.ToString ();
}
}
else
{
rateLimitErrorOccurred = false;
apiAbortErrorCode = -1;
apiPostAbortErrorMessage = "WHOOPS! Looks like your session has expired or become invalid. Try Signing in again to revalidate your session: \n\n" + e.InnerException.ToString ();
}
uploadedImgID = null;
}
}
//generic call back for any post calls
void OnPostUploadComplete(object sender, FacebookApiEventArgs args)
{
try
{
var json = args.GetResultData();
TruLogger.LogError(json.ToString());
apiPostStatusMessage = "FB post successfully submitted";
//FacebookPostStatusUpdatedEvent.Invoke("FB post successfully submitted");
}
catch (Exception e)
{
apiPostStatusMessage = "FB post failed to submit";
//FacebookPostStatusUpdatedEvent.Invoke("FB post failed to submit");
TruLogger.LogError (e.Message);
TruLogger.LogError (e.InnerException.ToString());
FacebookOAuthException oEx = (FacebookOAuthException)(e.InnerException);
if (oEx != null) {
TruLogger.LogError ("Error Type: " + oEx.ErrorType);
TruLogger.LogError ("Error Code: " + oEx.ErrorCode);
TruLogger.LogError ("Error Subcode: " + oEx.ErrorSubcode);
apiAbortErrorCode = oEx.ErrorCode;
if (apiAbortErrorCode == 32 || apiAbortErrorCode == 4)
{
rateLimitErrorOccurred = true;
apiPostAbortErrorMessage = "WHOOPS! Looks like you have exceeded the daily API rate quota for one or more of your feeds. You may have to wait between 1-24 hours until Facebook replenishes your balance for these feeds: \n\n" + e.InnerException.ToString ();
}
else
{
rateLimitErrorOccurred = false;
apiPostAbortErrorMessage = "WHOOPS! Looks like your session has expired or become invalid. Try Signing in again to revalidate your session: \n\n" + e.InnerException.ToString ();
}
}
else
{
rateLimitErrorOccurred = false;
apiAbortErrorCode = -1;
apiPostAbortErrorMessage = "WHOOPS! Looks like your session has expired or become invalid. Try Signing in again to revalidate your session: \n\n" + e.InnerException.ToString ();
}
}
}
Facebook doesn't directly allow to upload multiple videos or photos with videos on the business page. However, it is possible on a personal page so as an alternate solution you can create a post on a personal page and share it on the business page.
Check this video for more information: https://www.youtube.com/watch?v=AoK_1S71q1o

Prevent sending email and show message via plug-in

I am writing crm2011 plugin in "Email" entity with "Send" Message of Pre_operation. What i want to do is when i click "Send" button in email entity, I do the necessary checking before send. If the checking is not correct, I want to prevent and stop the sending email and show "the alert message" and stop the second plugin(this plugin send email and create the associated entity to convert "Case"). Please give me some suggestion for that plugin?
Should i use pre-Validation stage or Pre_operation state? And how can I return false to stop plugin.
public void Execute(IServiceProvider serviceProvider)
{
try
{
string message = null;
_serviceProvider = serviceProvider;
_context = (IPluginExecutionContext)
serviceProvider.GetService(typeof(IPluginExecutionContext));
_serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
_currentUser = _context.UserId;
message = _context.MessageName.ToLower();
if (message == "send")
{
if (_context.InputParameters != null && _context.InputParameters.Contains("EmailId"))
{
object objEmailId = _context.InputParameters["EmailId"];
if (objEmailId != null)
{
_emailId = new Guid(objEmailId.ToString());
FindEmailInfo();
if (_email != null)
{
if (_email.Attributes.Contains("description") && _email.Attributes["description"] != null)//Email descritpion is not null
{
string emaildescription = StripHTML();
//Find KB Article prefix no in system config entity
serviceguideprefix = "ServiceGuidesPrefix";
QueryByAttribute query = new QueryByAttribute("ppp_systemconfig");
query.ColumnSet = new ColumnSet(true);
query.AddAttributeValue(sysconfig_name, serviceguideprefix);
EntityCollection sysconfig = _service.RetrieveMultiple(query);
if (sysconfig.Entities.Count > 0)
{
Entity e = sysconfig.Entities[0];
if (e.Attributes.Contains("ppp_value"))
{
ppp_value = e.Attributes["ppp_value"].ToString();
}
}
if (ppp_value != null && ppp_value != string.Empty)
{
//var matches = Regex.Matches(emaildescription, #"KBA-\d*-\w*").Cast<Match>().ToArray();
var matches = Regex.Matches(emaildescription, ppp_value + #"-\d*-\w*").Cast<Match>().ToArray();
//ReadKBNo(emaildescription);
foreach (Match kbnumber in matches)
{
EntityCollection kbarticlecol = FindKBArticleIds(kbnumber.ToString());
if (kbarticlecol.Entities.Count > 0)
{
Entity kbariticle = kbarticlecol.Entities[0];
if (kbariticle.Attributes.Contains("mom_internalkm"))
{
bool internalserviceguide = (bool)kbariticle.Attributes["mom_internalkm"];
if (internalserviceguide) found = true;
else found = false;
}
else found = false;
}
}
}
if (found)
{
//-----
}
}
}
}
}
}
}
catch (Exception ex)
{
throw new InvalidPluginExecutionException(ex.Message, ex);
}
}
Well stopping the plugin is dead easy you just throw InvalidPluginException, the message you give it will be shown to the user in a alert window. You will have to do this on the pre of the send. In this case I don't think it will matter if its pre-validation or pre-operation.
Edit:
Yes, you should throw an InvalidPluginException even if no exception has happened in code. I accept this isnt what we would normally do, but its the way its meant to work. Msdn has more details: http://msdn.microsoft.com/en-us/library/gg334685.aspx
So for example the code would look like:
public void Execute(IServiceProvider serviceProvider)
{
try
{
//This is where we validate the email send
if(emailIsOkay)
{
//Do something
}
else if(emailIsNotOkay)
{
//Throw and exception that will stop the plugin and the message will be shown to the user (if its synchronous)
throw new InvalidPluginExecutionException("Hello user, your email is not correct!!");
}
}
catch (InvalidPluginExecutionException invalid)
{
//We dont to catch exception for InvalidPluginExecution, so just throw them on
throw;
}
catch (Exception ex)
{
//This exception catches if something goes wrong in the code, or some other process.
throw new InvalidPluginExecutionException(ex.Message, ex);
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Crm;
using Microsoft.Xrm.Sdk;
using System.ServiceModel;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Crm.Sdk.Messages;
using System.Text.RegularExpressions;
using System.Xml.Linq;
namespace SendEmail
{
public class Email : IPlugin
{
public void Execute(IServiceProvider serviceprovider)
{
IPluginExecutionContext context = (IPluginExecutionContext)serviceprovider.GetService(typeof(IPluginExecutionContext));
if (!(context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity))
return;
//entity
Entity ent = (Entity)context.InputParameters["Target"];
if (ent.LogicalName != "entityName")//EntityName
throw new InvalidPluginExecutionException("Not a Service Request record! ");
//service
IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceprovider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService _service = serviceFactory.CreateOrganizationService(context.UserId);
string Email="";
if (ent.Contains("emailidfiled"))
Email = (string)ent["emailidfiled"];
#region email template
QueryExpression query = new QueryExpression()
{
EntityName = "template",
Criteria = new FilterExpression(LogicalOperator.And),
ColumnSet = new ColumnSet(true)
};
query.Criteria.AddCondition("title", ConditionOperator.Equal, "templateName");
EntityCollection _coll = _service.RetrieveMultiple(query);
if (_coll.Entities.Count == 0)
throw new InvalidPluginExecutionException("Unable to find the template!");
if (_coll.Entities.Count > 1)
throw new InvalidPluginExecutionException("More than one template found!");
var subjectTemplate = "";
if (_coll[0].Contains("subject"))
{
subjectTemplate = GetDataFromXml(_coll[0]["subject"].ToString(), "match");
}
var bodyTemplate = "";
if (_coll[0].Contains("body"))
{
bodyTemplate = GetDataFromXml(_coll[0]["body"].ToString(), "match");
}
#endregion
#region email prep
Entity email = new Entity("email");
Entity entTo = new Entity("activityparty");
entTo["addressused"] =Email;
Entity entFrom = new Entity("activityparty");
entFrom["partyid"] = "admin#admin.com";
email["to"] = new Entity[] { entTo };
email["from"] = new Entity[] { entFrom };
email["regardingobjectid"] = new EntityReference(ent.LogicalName, ent.Id);
email["subject"] = subjectTemplate;
email["description"] = bodyTemplate;
#endregion
#region email creation & sending
try
{
var emailid = _service.Create(email);
SendEmailRequest req = new SendEmailRequest();
req.EmailId = emailid;
req.IssueSend = true;
GetTrackingTokenEmailRequest wod_GetTrackingTokenEmailRequest = new GetTrackingTokenEmailRequest();
GetTrackingTokenEmailResponse wod_GetTrackingTokenEmailResponse = (GetTrackingTokenEmailResponse)
_service.Execute(wod_GetTrackingTokenEmailRequest);
req.TrackingToken = wod_GetTrackingTokenEmailResponse.TrackingToken;
_service.Execute(req);
}
catch (Exception ex)
{
throw new InvalidPluginExecutionException("Email can't be saved / sent." + Environment.NewLine + "Details: " + ex.Message);
}
#endregion
}
private static string GetDataFromXml(string value, string attributeName)
{
if (string.IsNullOrEmpty(value))
{
return string.Empty;
}
XDocument document = XDocument.Parse(value);
// get the Element with the attribute name specified
XElement element = document.Descendants().Where(ele => ele.Attributes().Any(attr => attr.Name == attributeName)).FirstOrDefault();
return element == null ? string.Empty : element.Value;
}
}
}

Dynamics CRM 4.0 plugin fails when triggered by API

I have a plugin registered for when an account is created or updated, this is registered for the post stage.
The plugin works fine when a user creates or updates an account through the CRM interface, however when an account is created uging the API the plugin fails with the ever helpful 'server was unable to process the request' message. if an account is updated through the api the plugin also works correctly.
anyone have any ideas why?
UPDATE:
here is the create code
account = new CrmService.account();
account.ownerid = new CrmService.Owner();
account.ownerid.Value = new Guid("37087BC2-F2F0-DC11-A856-001E0B617486");
account.ownerid.type = CrmService.EntityName.systemuser.ToString();
account.name = model.CompanyName;
account.address1_line1 = model.Address1;
account.address1_line2 = model.Address2;
account.address1_stateorprovince = model.County;
account.address1_country = model.Country;
account.address1_city = model.TownCity;
account.address1_postalcode = model.PostCode;
account.new_companytype = new CrmService.Picklist();
switch (model.SmeType)
{
case SmeType.Micro:
account.new_companytype.Value = 1;
break;
case SmeType.Small:
account.new_companytype.Value = 2;
break;
case SmeType.Medium:
account.new_companytype.Value = 3;
break;
default:
break;
}
account.new_balancesheettotal = new CrmService.CrmMoney();
account.new_balancesheettotal.Value = preQualModel.BalanceSheetGBP;
account.revenue = new CrmService.CrmMoney();
account.revenue.Value = preQualModel.SalesTurnoverGBP;
if (model.Website != null)
{
account.websiteurl = model.Website.ToString();
}
account.numberofemployees = new CrmService.CrmNumber();
account.numberofemployees.Value = (int)preQualModel.NumEmployees;
accountGuid = svc.Create(account);
account.accountid = new CrmService.Key();
account.accountid.Value = accountGuid;
Here is the plugin code:
public void Execute(IPluginExecutionContext context)
{
DynamicEntity entity = null;
// Check if the InputParameters property bag contains a target
// of the current operation and that target is of type DynamicEntity.
if (context.InputParameters.Properties.Contains(ParameterName.Target) &&
context.InputParameters.Properties[ParameterName.Target] is DynamicEntity)
{
// Obtain the target business entity from the input parmameters.
entity = (DynamicEntity)context.InputParameters.Properties[ParameterName.Target];
// TODO Test for an entity type and message supported by your plug-in.
if (entity.Name != EntityName.account.ToString()) { return; }
// if (context.MessageName != MessageName.Create.ToString()) { return; }
}
else
{
return;
}
if (entity!=null && !entity.Properties.Contains("address1_postalcode"))
{
return;
}
if (context.Depth > 2)
{
return;
}
try
{
// Create a Microsoft Dynamics CRM Web service proxy.
// TODO Uncomment or comment out the appropriate statement.
// For a plug-in running in the child pipeline, use this statement.
// CrmService crmService = CreateCrmService(context, true);
// For a plug-in running in the parent pipeline, use this statement.
ICrmService crmService = context.CreateCrmService(true);
#region get erdf area from database
string postCode = entity.Properties["address1_postalcode"].ToString();
postCode = postCode.Replace(" ", ""); //remove spaces, db stores pcodes with no spaces, users usually enter them, e.g b4 7xg -> b47xg
string erdfArea = "";
SqlConnection myConnection = new SqlConnection(#"REDACTED");
try
{
myConnection.Open();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
try
{
SqlDataReader myReader = null;
SqlCommand myCommand = new SqlCommand("select ErdfAreaType from dim.Locality WHERE PostCode = '" + postCode+"'",
myConnection);
myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
erdfArea = myReader["ErdfAreaType"].ToString();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
try
{
myConnection.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
#endregion
entity.Properties["new_erdfarea"] = erdfArea;
crmService.Update(entity);
}
catch (System.Web.Services.Protocols.SoapException ex)
{
throw new InvalidPluginExecutionException(
String.Format("An error occurred in the {0} plug-in.",
this.GetType().ToString()),
ex);
}
}
Sometimes it can be difficult to see the actual source of an error in plugins. In moments like this tracing is your friend. You can use this tool to enable tracing. When you have the trace files, try to search them for the error you got in your exception. This should tell you more details about what is failing.
Turns out this was due to me expecting data that was not there due to some weird behaviour in CRM.
I was taking the dynamicEntity passed to the plugin like so
entity = (DynamicEntity)context.InputParameters.Properties[ParameterName.Target];
But this was missing critical things like accountid. fixed it by using the PostEntityImage entity instead, which had all of the expected data like so
entity = (DynamicEntity)context.PostEntityImages[ParameterName.Target];

apache HttpClient to access facebook

Any examples, tips, guidance for the following scenario?
I have used Apache HttpClient to simulate the functionality of browser to access facebook through java application. to do that first i have to provide user credentials. i have used examples provided in the following web site.
http://svn.apache.org/viewvc/httpcomponents/oac.hc3x/trunk/src/examples/
But non of these methods works for facebook, following is the test code i have written for this purpose. i have not provided the all the methods written, only the method used to login to the facebook account is given here. relay appreciate any help
private static int connectAndLogin(String email, String pass){
logger.trace("Facebook: =========connectAndLogin begin===========");
String httpResponseBody = getMethod("http://www.facebook.com/login.php");
if(httpResponseBody == null){
//Why don't we try again?
try
{
Thread.sleep(1000);
}
catch (InterruptedException e)
{
logger.trace(e.getMessage());
}
httpResponseBody = getMethod("http://www.facebook.com/login.php");
}
logger.trace("Facebook: ========= get login page ResponseBody begin===========");
logger.trace(httpResponseBody);
logger.trace("Facebook: +++++++++ get login page ResponseBody end+++++++++");
logger.trace("Facebook: Initial cookies: ");
List<Cookie> cookies = getCookies();
if (cookies.isEmpty()) {
logger.trace("Facebook: None");
} else {
for (int i = 0; i < cookies.size(); i++) {
logger.trace("Facebook: - " + cookies.get(i).toString());
}
}
if(httpResponseBody == null){
logger.warn("Facebook: Warning: Failed to get facebook login page.");
}
try
{
HttpPost httpost = new HttpPost("http://www.facebook.com/login.php");
List <NameValuePair> nvps = new ArrayList <NameValuePair>();
nvps.add(new BasicNameValuePair("email", email));
nvps.add(new BasicNameValuePair("pass", pass));
//don't know if is this necessary
nvps.add(new BasicNameValuePair("login", ""));
httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
logger.info("Facebook: #executing post method to:" + "http://www.facebook.com/login.php");
HttpResponse loginPostResponse = getHttpClient().execute(httpost);
HttpEntity entity = loginPostResponse.getEntity();
logger.trace("Facebook: Login form post: " + loginPostResponse.getStatusLine());
if (entity != null) {
logger.trace("Facebook: "+EntityUtils.toString(entity));
entity.consumeContent();
} else {
logger.error("Facebook: Error: login post's response entity is null");
return FacebookErrorCode.kError_Login_GenericError;
}
logger.trace("Facebook: Post logon cookies:");
cookies = getCookies();
if (cookies.isEmpty()) {
logger.trace("Facebook: None");
} else {
for (int i = 0; i < cookies.size(); i++) {
logger.trace("Facebook: - " + cookies.get(i).toString());
}
}
int statusCode = loginPostResponse.getStatusLine().getStatusCode();
logger.info("Facebook: Post Method done(" + statusCode + ")");
switch(statusCode){
case 100: break;//we should try again;
case 301:
case 302:
case 303:
case 307:
{
//redirect
// Header[] headers = loginPostResponse.getAllHeaders();
// for (int i=0; i<headers.length; i++) {
// logger.trace("Facebook: "+headers[i]);
// }
// Header locationHeader = loginPostResponse.getFirstHeader("location");
// if(locationHeader != null){
// homePageUrl = locationHeader.getValue();
// logger.info("Facebook: Redirect Location: " + homePageUrl);
// if(homePageUrl == null
// || !homePageUrl.contains("facebook.com/home.php")){
// logger.error("Facebook: Login error! Redirect Location Url not contains \"facebook.com/home.php\"");
// return FacebookErrorCode.kError_Login_GenericError;
// }
// } else {
// logger.warn("Facebook: Warning: Got no redirect location.");
// }
}
break;
default:;
}
}
catch (IOException ioe)
{
logger.error("Facebook: IOException\n" + ioe.getMessage());
return FacebookErrorCode.kError_Global_ValidationError;
}
logger.trace("Facebook: =========connectAndLogin end==========");
return FacebookErrorCode.Error_Global_NoError;
}
The following code, based on that sample, worked for me:
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet("http://www.facebook.com/login.php");
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
System.out.println("Login form get: " + response.getStatusLine());
if (entity != null) {
entity.consumeContent();
}
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("http://www.facebook.com/login.php");
List <NameValuePair> nvps = new ArrayList <NameValuePair>();
nvps.add(new BasicNameValuePair("email", "******"));
nvps.add(new BasicNameValuePair("pass", "*******"));
httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
response = httpclient.execute(httpost);
entity = response.getEntity();
System.out.println("Double check we've got right page " + EntityUtils.toString(entity));
System.out.println("Login form get: " + response.getStatusLine());
if (entity != null) {
entity.consumeContent();
}
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());
}
}
httpclient.getConnectionManager().shutdown();
I am not sure if your code was managing properly cookies (and session id kept within one of them), maybe that was the problem. Hope this will help you.
Just to make clear version issue: I was using HttpClient version 4.X, not the old one (3.X). They differ significantly.
Perhaps you should use a tool, such as Selenium
Have you taken a look at HtmlUnit. It wraps the HttpClient to create a headless Java browser, with javaScript execution. This way you are not trying to hack the individual forms all the time.