I'm trying to copy url contents with user info.
First, the user log in and then the page show the user info. I want to copy that info to a String.
I am using this:
try {
variable1 = new Scanner(new URL("https://example.com/hello").openStream(), "UTF-8").useDelimiter("\\A").next();
}catch (MalformedURLException e) {
System.out.println("The URL is not valid.");
}catch (IOException e) {
System.out.println("The URL is not valid.");
}
But I am getting the content in the login page...(as the user never logged in).
I thing maybe missing the cookie id in the request header. The cookie id is in the header of the response after the login request finished.
Related
I am using CamFind API for image recognition in my app. I am following CamFind Tutorial
but stuck at how to get response from that API after posting data? How you got my question.
try this code
try {
HttpResponse<JsonNode> request = Unirest
.post("https://camfind.p.mashape.com/image_requests")
.header("X-Mashape-Authorization",
"A0MYOpCsdfasdgadfadafgdj7vsdfe")
.field("image_request[locale]", "en_US")
.field("image_request[image]",
new File("your Image path")).asJson();
String body = request.getBody().toString();
Log.v("body", body);
} catch (UnirestException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
now the body string contain the json response String with a Token variable inside it
and to get the recognition name do the same again, but remove the fields and add the Token value after the url
so it will look like this:
https://camfind.p.mashape.com/image_requests/(Token Vlaue)
now the body string will contain the name value
First, I can log in my facebook and I already save access token in SharedPreferences.
However, when I try to this code:
JSONObject json_data = null;
try
{
JSONObject response = Util.parseJson(new Facebook(Define.APP_ID).request("me/friends"));
JSONArray jArray = response.getJSONArray("data");
json_data = jArray.getJSONObject(0);
String name = json_data.getString("name");
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (JSONException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
catch (FacebookError e)
{
e.printStackTrace();
}
I got an error "An active access token must be used to query information about the current user".
What should I do? I have access token already.
Isn't it better to use Facebook SDK for Android 3.0 which handles almost everything for you. There is method executeMyFriendsRequestAsync(Session session, Request.GraphUserListCallback callback) from Request class which returns list of your friends in callback. Here is getting started guide: https://developers.facebook.com/docs/getting-started/facebook-sdk-for-android/3.0 . If you use the sample code from this guide and change the type of request which is executed you will get the same information you're trying to get in code you provided.
You shoudn't do any request from Facebook Object directly. You have to create Facebook Object first and then set the AccessToken, Expiry Time and then do the requests as below.
FaceBook fb = new FaceBook(APP_ID);
fb.setAccessToken("youraccesstoken");
fb.setAccessExpires(expires);//expires is your milliseconds time.
Then you do your requests as fb.request("me/friends");
Your are requesting the information without a valid authenticated Session. So you are getting that error. Do authentication and set the access token then you get no problem
I found an example
try {
String data = "YOUR REQUEST BODY HERE";
//
CredentialsProvider credProvider = new BasicCredentialsProvider();
credProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
new UsernamePasswordCredentials("YOUR USER NAME HERE", "YOUR PASSWORD HERE"));
//
DefaultHttpClient http = new DefaultHttpClient();
http.setCredentialsProvider(credProvider);
//
HttpPut put = new HttpPut("YOUR HTTPS URL HERE");
try {
put.setEntity(new StringEntity(data, "UTF8"));
} catch (UnsupportedEncodingException e) {
Log.e(TAG, "UnsupportedEncoding: ", e);
}
put.addHeader("Content-type","SET CONTENT TYPE HERE IF YOU NEED TO");
HttpResponse response = http.execute(put);
Log.d(TAG, "This is what we get back:"+response.getStatusLine().toString()+", "+response.getEntity().toString());
} catch (ClientProtocolException e) {
//
Log.d(TAG, "Client protocol exception", e);
} catch (IOException e) {
//
Log.d(TAG, "IOException", e);
}
but I have to send a string in the format of the authorization: <Login>#<ID>:<Passsword>
how to do this?
Are you sure that your server is indeed using basic authentication? If it is, you should set the credentials like this:
new UsernamePasswordCredentials("Login#ID", "Passsword");
Otherwise check what the actual authentication protocol is and implement it (send auth info in header, or as part of URL or as POST parameters, etc.)
You should have a look first what actually HTTP Basic is: http://en.m.wikipedia.org/wiki/Basic_access_authentication#section_3
Your question aims not at HTTP Basic and should not be used at all due to being inherently insecure.
I presume what you ask for should be part of the URL. Even with additional measures like SSL I still would not embed credentials in the URL.
HTTP Basic defines how the username and password must be encrypted (actually hashed). No way to have HTTP and the format you asked for.
I am new to Facebook API. Trying the FQL Query from the Graph API for the first time using this link.
I am trying to get photos from the album with the album id. When I request using Facebook object with https://graph.facebook.com/10150146071791729/photos&access_token=ACCESS_TOKEN URL, I am getting the following response (before parsing to JSON object). {"id":"https://graph.facebook.com/10150146071791729/photos","shares":2}. And I confirmed it by printing the length of the JSON object after parsing, which is 2. When I copy and paste the same URL in the web browser, I am getting the expected response (the response in FQL Query I got). Here is my code.
public void onComplete(Bundle values) {
String token = facebook.getAccessToken();
System.out.println("Token: " + token);
try {
String response = facebook.request("https://graph.facebook.com/10150146071791729/photos&access_token=ACCESS_TOKEN");
System.out.println("response :"+response);
JSONObject obj = Util.parseJson(response);
System.out.println("obj length : " + obj.length());
Iterator iterator = obj.keys();
while(iterator.hasNext()){
String s = (String)iterator.next();
System.out.println(""+s+" : "+obj.getString(s));
}
} catch (Throwable e) {
e.printStackTrace();
}
}
Note: I got access token from the FQL Query which is used in the URL. And I did not wrote any session (login/logout) logic as it is a test project.
Your request is wrong. It should be
"https://graph.facebook.com/10150146071791729/photos?access_token=ACCESS_TOKEN"
Replace the '&' after the photos with a '?'.
Two more things, you're making a Graph API query, not an FQL one.
Second, NEVER post your access tokens publicly. If I wanted to, I can now use your access token to edit your facebook information.
EDIT: When you use the Android Facebook SDK, you do not need to use the full graph path. Instead, use
facebook.request("10150146071791729/photos")
You do not need to add the access token as the Facebook object already has it. Hope this helps.
Because not much code has been provided except for the most relevant one, let me give you a couple of ways you can access Photos from an Album
FIRST METHOD (IF your wish to use the complete URL to make the request)
String URL = "https://graph.facebook.com/" + YOUR_ALBUM_ID
+ "/photos&access_token="
+ Utility.mFacebook.getAccessToken() + "?limit=10";
try {
HttpClient hc = new DefaultHttpClient();
HttpGet get = new HttpGet(URL);
HttpResponse rp = hc.execute(get);
if (rp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
String queryPhotos = EntityUtils.toString(rp.getEntity());
Log.e("PHOTOS RESULT", queryPhotos);
}
} catch (Exception e) {
e.printStackTrace();
}
SECOND METHOD (Without using the complete URL as #Vinay Shenoy mentioned earlier)
try {
Bundle paramUserInfo = new Bundle();
paramUserInfo.putString(Facebook.TOKEN, Utility.mFacebook.getAccessToken());
String resultPhotos = Utility.mFacebook.request("YOUR_ALBUM_ID/photos", paramUserInfo, "GET");
Log.e("PHOTOS", resultPhotos);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
On a personal note, I follow the first method almost entirely through my application. It lets me using the Paging for endless ListViews
That being said, when I need some quick data in between somewhere, I do rely on the second method. Both of them work and I hope either (or both) of them helps you.
I'm currently using Scribe to both authenticate and post non-media messages to Twitter successfully. This was very easy, my first test message posted with no issues. However, I can't seem to post photos at all. I have reviewed Twitter's instructions for posting with media, both here and here.
All of the Scribe/Twitter examples at Github are for non-media posts. It would be great if someone could provide a solid example of how to post photos to Twitter via Scribe!
I'm have two issues in particular:
1) My posts will not pass authorization. I've tried mimicking the examples I posted above, but nothing seems to work.
2) When converting the image from byte[] to a string, I only seem to get 4113 characters before it stops. From my understanding, this is well under the number of characters a String can hold.
Here is how I'm extracting the photo:
// GET PHOTO FILE AND FILE LENGTH
// INSTANTIATE UPLOAD VARIABLE WITH FILE LENGTH
File file = new File(photo); // ("photo" is a string path to the photo file)
int fileLength = (int) file.length();
uploadFile = new byte[fileLength];
// CREATE BUFFER INPUT STREAM OF FILE
BufferedInputStream inputStream;
try {inputStream = new BufferedInputStream(new FileInputStream(file));}
catch (FileNotFoundException e)
{
inputStream = null;
Toast.makeText(this.getApplicationContext(), "Buffer input stream error!", Toast.LENGTH_LONG).show();
}
// READ DATA FROM FILE INTO UPLOAD VARIABLE
// CLOSE INPUT STREAM
try {inputStream.read(uploadFile);}
catch (IOException e) {Toast.makeText(this.getApplicationContext(), "Read input stream to upload variable error!", Toast.LENGTH_LONG).show();}
try {inputStream.close();}
catch (IOException e) {Toast.makeText(this.getApplicationContext(), "Close input stream error!", Toast.LENGTH_LONG).show();}
After a LOT of research and piece milling code from various places I finally figured out what I was doing wrong. Here is an example of how to post photos to Twitter via Scribe OAuth:
NOTE: This assumes a few things...
1) You have already saved the photo and have the file path
2) You have already authenticated the user at some point and have a valid access Token
3) You MUST add apache-mime4j-0.6.jar & httpmime-4.0.1.jar to you libs folder and include them in your build path!!!
I really hope this helps someone! It's very easy to implement, but took a few days of troubleshooting to get it working correctly!
// BUILD OAUTH SERVICE
OAuthService oAuth = new ServiceBuilder()
.provider(TwitterApi.class)
.apiKey(YOUR_TWITTER_API_KEY) // REPLACE WITH YOUR OWN!!!
.apiSecret(YOUR_TWITTER_API_SECRET) // REPLACE WITH YOUR OWN!!!
.callback(YOUR_CALLBACK) // REPLACE WITH YOUR OWN!!!
.build();
// BUILD OAUTH REQUEST & SIGN IT RIGHT AWAY (OTHERWISE MULTIPART FORM MAY PREVENT SIGNING)
OAuthRequest request = new OAuthRequest(Verb.POST, "https://upload.twitter.com/1.1/statuses/update_with_media.json");
oAuth.signRequest(USER_ACCESS_TOKEN, request); // ENTER USER'S ACCESS TOKEN
// ADD MULTIPART FORM
try
{
MultipartEntity entity = new MultipartEntity();
entity.addPart("status", new StringBody(message)); // THIS IS THE TWITTER MESSAGE
entity.addPart("media", new FileBody(new File(photo))); // THIS IS THE PHOTO TO UPLOAD
ByteArrayOutputStream out = new ByteArrayOutputStream();
entity.writeTo(out);
request.addPayload(out.toByteArray());
request.addHeader(entity.getContentType().getName(), entity.getContentType().getValue());
}
catch (UnsupportedEncodingException e) {e.printStackTrace();}
catch (IOException e) {e.printStackTrace();}
// SEND REQUEST
try {response = new JSONObject (request.send().getBody());}
catch (JSONException e) {Log.e("YOUR_APP_TAG", "JSONException Thrown: " + e.getMessage());}