Getting list of Facebook page status' updates in Android - java

How can I pull a list of all of a Facebook page's status updates in Android? This seems like such a simple question, but seems to be a very difficult task. I don't want to have to use the SDK. I thought it would be simple like twitter... http request and parse the resulting json. From research, the only way I seem to be able to get JSON out of Facebook is with their Open Graph, which requires registering an application, and generating access tokens. This seems like overkill just to try and get public status updates. Is there something I'm missing?
Im not trying to make any status updates, or get any other information. Im only wanting to read the public statuses off of a single Facebook page.

You have to Use Url like this
String url = "https://graph.facebook.com/" +facebook_User_name +"/statuses&limit=20&access_token=" + access_token
you have to pass that url to HttpGet method for getting information.
HttpGet httpget = new HttpGet(url);
HttpResponse response;
try {
response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
result= convertStreamToString(instream);
JSONObject json = new JSONObject(result);
JSONArray valArray = json.getJSONArray("data");
for(int i=0;i<valArray.length();i++) {
String info = main_object.getString("message");
}
instream.close();
}
}
catch (ClientProtocolException e) {
e.printStackTrace();
}

Please use this url to get the list of posts from facebook page
https://graph.facebook.com/"YOUR PAGE NAME"/feed?access_token="YOUR ACCESS TOKEN"
If you want to get your own facebook posts details use the beleow url
https://graph.facebook.com/me/feed?access_token="YOUR ACCESS TOKEN"

Related

How to write / convert CURL for Android java

I am trying to implement the MOT history API https://dvsa.github.io/mot-history-api-documentation/ and they give an example using CURL which works with the supplied api key successfully when using an online CURL tool.
I am trying to implement this in Android and realise I have to use something like HttpPost rather than CURL, this is my code:
//Tried with full URL and by adding the registration as a header.
//HttpPost httpPost = new HttpPost("https://beta.check-mot.service.gov.uk/trade/vehicles/mot-tests?registration=" + reg_selected);
HttpPost httpPost = new HttpPost("https://beta.check-mot.service.gov.uk/trade/vehicles/mot-tests");
httpPost.addHeader("Content-Type", "application/json");
httpPost.addHeader("Accept", "application/json+v6");
httpPost.addHeader("x-api-key", "abcdefgh123456");
httpPost.addHeader("registration", reg_selected);
StringEntity entity = new StringEntity(jsonObj.toString(), HTTP.UTF_8);
httpPost.setEntity(entity);
HttpClient client = new DefaultHttpClient();
try {
HttpResponse response = client.execute(httpPost);
if (response.getStatusLine().getStatusCode() == 200) {
InputStream inputStream = response.getEntity().getContent();
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String readLine = bufferedReader.readLine();
String jsonStr = readLine;
JSONObject myJsonObj = new JSONObject(jsonStr);
}else if (response.getStatusLine().getStatusCode() == 400){
//Bad Request Invalid data in the request. Check your URL and parameters
error_text = "Bad Request";
}else if (response.getStatusLine().getStatusCode() == 403){
//Unauthorised – The x-api-key is missing or invalid in the header
error_text = "Authentication error"; //<<<< FAILS HERE 403
}
response.getStatusLine().getStatusCode() returns • "403 – Unauthorised – The x-api-key is missing or invalid in the header".
However the x-api-key that I use works correctly with the online CURL test so the actual key is correct but how I am adding it to my android code request must be invalid or similar.
Can anyone throw any light as to the correct way to convert the CURL into Android java so that the server does not return 403?
Thanks
It's easy to do with Jsoup:
// CREATE CONNECTION
Connection conn=Jsoup.connect("URL_GOES_HERE");
// ADD POST/FORM DATA
conn.data("KEY", "VALUE");
// ADD HEADERS HERE
conn.header("KEY", "VALUE");
// SET METHOD AS POST
conn.method(Connection.Method.POST);
// ACCEPT RESPONDING CONTENT TYPE
conn.ignoreContentType(true);
try
{
// GET RESPONSE
String response = conn.execute().body();
// USE RESPONSE HERE
// CREATE JSON OBJECT OR ANYTHING...
} catch(HttpStatusException e)
{
int status = e.getStatusCode();
// HANDLE HTTP ERROR HERE
} catch (IOException e)
{
// HANDLE IO ERRORS HERE
}
Ps: I guess you are confused with Header and Post Data. The key etc (Credentials) must be used as Post Data and Content Type etc as Header.

url.openStream() and httpClient.execute() does not work for some webpages

I have a block of codes to read URL page content, This code is working good for many pages but does not work for some pages like the link below:
https://www.deutschepost.com/en/business-customers.html/robots.txt
my code is something like this:
String url = https://www.deutschepost.com/en/business-customers.html/robots.txt
HttpGet request = new HttpGet(url);
//requesting the data using execute();
CloseableHttpResponse response = httpClient.execute(request);
//below is for openStream();
InputStream robotTxtStream = new URL(url).openStream();
I am not getting any response not even exception from both "openStream();" or"execute()".
Thanks in advance!!

use docusign api creates envelopes, error: Object moved

I consulted the API documentation and sent it successfully in api explorer-> Envelopes: create. I also got json & request path & token. I used httpclient post in java and received Object moved Object moved to here . Does anyone know what I missed?
`
DocsignDocument docsignDocument = new DocsignDocument();
docsignDocument.setDocumentBase64
docsignDocument.setDocumentId("1");
docsignDocument.setFileExtension("pdf");
docsignDocument.setName("Test.pdf");
list.add(docsignDocument);
Recipients recipients = new Recipients();
Signers signers = new Signers();
signers.setEmail("xxxx");
signers.setName("Qin");
signers.setRecipientId("1");
Signers signers1 = new Signers();
signers1.setEmail("xxx#qq.com");
signers1.setName("OYX");
signers1.setRecipientId("2");
List<Signers> signersList = new ArrayList<>();
signersList.add(signers);
signersList.add(signers1);
recipients.setSigners(signersList);
dataJson.put("documents",list);
dataJson.put("emailSubject","TEST");
dataJson.put("recipients",recipients);
dataJson.put("status","sent");
String data = dataJson.toJSONString();
String results2 = HttpDocusignUtils.httpPostJson("https://account-d.docusign.com/restapi/v2.1/accounts/xxx/envelopes",access_token,data)`
post request:
public static String httpPostJson(String uri, String token, String obj) {
String result = "";
try {
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(uri);
httpPost.addHeader("Content-Type", "application/json"); // 添加请求头
httpPost.addHeader("Authorization","Bearer "+token);
httpPost.addHeader("Accept-Encoding","gzip,deflate,sdch");
httpPost.setEntity(new StringEntity(obj));
System.out.println(httpPost);
HttpResponse response = httpclient.execute(httpPost);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instreams = entity.getContent();
result = convertStreamToString(instreams);
System.out.println(result);
}
} catch (Exception e) {
e.getMessage();
}
return result;
}
https://account-d.docusign.com/restapi/v2.1/accounts/xxx/envelopes is not a valid DocuSign endpoint.
The Account Server (account-d.docusign.com) is used to get a token and make a UserInfo call to determine the correct base URL for a particular account.
Because you're in the Demo environment, your base url will begin with https://demo.docusign.net
Well, one issue is that the the Document model in Java is Document from
import com.docusign.esign.model.Document;
To debug, I suggest using the DocuSign API logging feature. Then update (edit) your question to include the JSON shown in the log.
Were you able to run the code examples for Java? See eg-03-java-auth-code-grant
Also, please tell us (by editing your question) what you are trying to do.
Creates envelopes - Use Base Url in Api Call
https://demo.docusign.net/restapi/v2.1/accounts/
Error Reason is use Wrong url - https://account-d.docusign.com/restapi/v2.1/accounts/
DocuSign Developers Documentation

Curl equivalent POST in java for SOLR

I just started working with SOLR. I want to index some html pages and got this from the documentation:
curl "http://localhost:8983/solr/update/extract?literal.id=doc1&commit=true" -F "myfile=#/home/binaryplease/workspace/SOLRTest/HTMLPages/hello2.html"
Which works as expected as the query returns the expecteed results.
How would I do this exact POST inside a java application?
I tried this as I dont know how to do it with the HttpClient but it's not working:
String command = "curl \"http://localhost:8983/solr/update/extract?literal.id=doc1&commit=true\" -F \"myfile=#\"" +f.getAbsoluteFile() + "\"";
try {
proc = Runtime.getRuntime().exec(command );
InputStream in = proc.getInputStream();
InputStream err = proc.getErrorStream();
System.out.println("Inputstream " + getStringFromInputStream(in));
System.out.println("Errorstream " + getStringFromInputStream(err));
} catch (IOException e) {
e.printStackTrace();
}
What would be the correct way to index a html file in SOLR and do a query using java?
I would appreciate an example.
EDIT: I got this now which still isn't working:
HttpClient httpclient = HttpClients.createDefault();
HttpPost httppost = new HttpPost("http://localhost:8983/solr/update/extract?literal.id=doc1&commit=true");
// Request parameters and other properties.
List<NameValuePair> params = new ArrayList<NameValuePair>(2);
params.add(new BasicNameValuePair("myfile", "#/home/binaryplease/workspace/SOLRTest/HTMLPages/hello3.html"));
httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
//Execute and get the response.
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
try {
System.out.println("Content " + getStringFromInputStream(instream));
} finally {
instream.close();
}
}
}
What am i doing wrong?
You should be using the SolJ client for accessing Solr from Java, which will likely be much easier for you than going the the HTTP interface:
SolrJ is an API that makes it easy for Java applications to talk to
Solr. SolrJ hides a lot of the details of connecting to Solr and
allows your application to interact with Solr with simple high-level
methods.
The center of SolrJ is the org.apache.solr.client.solrj package, which
contains just five main classes. Begin by creating a SolrServer, which
represents the Solr instance you want to use. Then send SolrRequests
or SolrQuerys and get back SolrResponses.
SolrServer is abstract, so to connect to a remote Solr instance,
you'll actually create an instance of HttpSolrServer, which knows how
to use HTTP to talk to Solr.
https://cwiki.apache.org/confluence/display/solr/Using+SolrJ
The setup is pretty easy:
String urlString = "http://localhost:8983/solr";
SolrServer solr = new HttpSolrServer(urlString);
And so are queries:
SolrQuery parameters = new SolrQuery();
parameters.set("q", mQueryString);
QueryResponse response = solr.query(parameters);
SolrDocumentList list = response.getResults();
Same thing with indexing:
String urlString = "http://localhost:8983/solr";
SolrServer solr = new HttpSolrServer(urlString);
SolrInputDocument document = new SolrInputDocument();
document.addField("id", "552199");
document.addField("name", "Gouda cheese wheel");
document.addField("price", "49.99");
UpdateResponse response = solr.add(document);
// Remember to commit your changes!
solr.commit();

twitter streaming api - set filter in http post request (apache httpcomponents)

I'm trying out the twitter streaming api. I could succesfully filter tweets by using curl, as stated here:
curl -d #tracking http://stream.twitter.com/1/statuses/filter.json -u <user>:<pass>
where tracking is a plain file with the content:
track=Berlin
Now I tried to do the same thing in JavaSE, using Apache's HTTPComponents:
UsernamePasswordCredentials creds = new UsernamePasswordCredentials(<user>, <pass>);
DefaultHttpClient httpClient = new DefaultHttpClient();
httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, creds);
HttpPost httpPost = new HttpPost("http://stream.twitter.com/1/statuses/filter.json");
HttpParams params = new BasicHttpParams();
params = params.setParameter("track", "Berlin");
httpPost.setParams(params);
try {
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
String t;
BufferedReader br = new BufferedReader(new InputStreamReader(instream));
while(true) {
t = br.readLine();
if(t != null) {
linkedQueue.offer(t);
}
}
}
} catch (IOException ioe) {
System.out.println(ioe.getMessage());
}
finally{
httpClient.getConnectionManager().shutdown();
}
When I run that, I get:
No filter parameters found. Expect at least one parameter: follow track
as a single entry in my linkedQueue. Seems the api wants the parameter in a different form, but cannot find any hint in the documentation. Can somebody share some experiences with the api or see any other problem with the code? Thanks!
EDIT
Putting the filter parameter into the params was a bad idea. As it's post data, it needs to be defined as an Entity before the request is being made:
StringEntity postEntity = new StringEntity("track=Berlin", "UTF-8");
postEntity.setContentType("application/x-www-form-urlencoded");
httpPost.setEntity(postEntity);
That's what I was doing wrong. Thanks Brian!
I suspect you need to post the data as the contents of your HTTP post. The man page for curl -d says:
(HTTP) Sends the specified data in a
POST request to the HTTP server, in
the same way that a browser does when
a user has filled in an HTML form and
presses the submit button. This will
cause curl to pass the data to the
server using the content-type
application/x-www-form-urlencoded.
so I believe you have to set that content type and put the contents of the tracking file in the body of your post.

Categories

Resources