I am trying to do a http post to my server to check if the login credentials are valid with help of this tutorial. I need to make a request to my server but i have to add Authorization, i get the string with the function getB64Auth from this answer. the function logs the right variable, (the same as i use with postman). But for some reason my program stops running if i run my code. I already tried adding the code from the comments but it didn't help.
What am i doing wrong?
private String getB64Auth (String login, String pass) {
String source=login+":"+pass;
String ret="Basic "+Base64.encodeToString(source.getBytes(),Base64.URL_SAFE| Base64.NO_WRAP);
Log.d("authy", ret);
return ret;
}
/** Called when the user clicks the Login button */
public void login(View view) {
// Getting username and password
EditText userText = (EditText) findViewById(R.id.inputLoginUsername);
EditText passText = (EditText) findViewById(R.id.inputLoginPassword);
String usernameInput = userText.getText().toString();
String passwordInput = passText.getText().toString();
String authorizationString = getB64Auth(usernameInput,passwordInput );
// Do something in response to button
// 1. Create an object of HttpClient
HttpClient httpClient = new DefaultHttpClient();
// 2. Create an object of HttpPost
// I have my real server name down here
HttpPost httpPost = new HttpPost("https://myservername.com/login");
// 3. Add POST parameters
httpPost.setHeader("Authorization", authorizationString);
// 5. Finally making an HTTP POST request
try {
HttpResponse response = httpClient.execute(httpPost);
Log.d("win", "win1");
// write response to log
Log.d("Http Post Response:", response.toString());
} catch (ClientProtocolException e) {
Log.d("fail", "Fail 3");
// Log exception
e.printStackTrace();
} catch (IOException e) {
Log.d("fail", "Fail 4");
// Log exception
e.printStackTrace();
}
}
When i run my code the app stops working, i can find the log authy but i cant find any fail succes logs.
The things i have changed in the example are step 3.
ive added my authorization there.
and removed step 4 cause i dont need it.
Working postman example, with the same request i want to make in android.
You can see I get a response, and only set Authorization on my request.
I cant find any decent post/authorization tutorials so i hope i'm looking at the right direction.
It's an android 4.* project
Just a few suggestions about such issues:
Check permissions (INTERNET is the one you would need)
Applications like Charles / Fiddler let you sniff the Http traffic from the device so you could investigate what is being sent
If the application is crashing - check the LogCat messages (for example it could contain a message explaining which permission is missing)
Regarding this message:
The application may be doing too much work on its main thread.
This usually means that you are doing some heavy operations in the main thread - for example parsing the Json from the Http response. Generally you'd like to do all these operations in a background thread and use the main one to update the UI only.
Related
I am using the Dirble Api and I am trying to test it to even get some results back but I think I might be doing it the wrong way. This is how I have been trying:
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("http://api.dirble.com/v2/songs?token={MY_PROVIDED_ACCESS_TOKEN}")
.build();
try {
Response response = client.newCall(request).execute();
System.out.println("Test " + response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
But I keep getting the error:
{"error":"Unauthorized. Invalid or expired token."}
I assumed that this meant the tokens they provided me are just not functioning. So I generated a new one and same result.
This is there guidelines:
https://dirble.com/api-doc#introduction
I cant see anything I am doing wrong but since I am a novice in http requests, I would like to check there is nothing wrong with how I am doing it before I contact them to say the my access codes aren't working.
Just as a demonstration the code will work, I am attempting to fetch some JSON data within my oncreate function. I know it should run on a different thread but I want to be sure the code successfully fetches my JSON before moving it into it's own thread.
The code is below:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
/***************************************************/
final String TAG = "PostFetcher";
final String SERVER_URL = "http://kylewbanks.com/rest/posts";
// final String TAG = "PostsActivity";
// List<Post> posts;
try {
//Create an HTTP client
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(SERVER_URL);
//Perform the request and check the status code
HttpResponse response = client.execute(post);
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
try {
//Read the server response and attempt to parse it as JSON
Reader reader = new InputStreamReader(content);
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setDateFormat("M/d/yy hh:mm a");
Gson gson = gsonBuilder.create();
List<JsonObject> posts = new ArrayList<JsonObject>();
Log.e(TAG, "Checking: " + posts);
// posts = Arrays.asList(gson.fromJson(reader, JsonObject[].class));
content.close();
} catch (Exception ex) {
Log.e(TAG, "Failed to parse JSON due to: " + ex);
}
} else {
Log.e(TAG, "Server responded with status code: " + statusLine.getStatusCode());
}
} catch(Exception ex) {
Log.e(TAG, "Failed to send HTTP POST request due to: " + ex);
}
}
When I run the code, I get the second to last exception message:
Server responded with status code: 500
Can anyone please tell me what I'm doing wrong?
You are sending a HttpPost request to (obviously) an website that uses RESTful styled API.
This means, it works with HTTP Verbs (GET, POST, PUT, DELETE).
If you want to read data and the read access never changes data, use GET.
If you want to update or replace data, user PUT or POST (put usually to replace, POST to change/add). However, JavaScript does (or did) only support GET and POST requests, so keep that in mind.
If you want to delete a resource or collection, use DELETE.
That being said: If you want to load data, use Get in your case HttpGet instead of HttpPost.
Also read more about RESTful web APIs.
Edit:
In fact, calling the given URL in Fiddler2 (as stated in the comment on the other answer) results a HTML website reporting the error:
You called this URL via POST, but the URL doesn't end in a slash and
you have APPEND_SLASH set. Django can't redirect to the slash URL
while maintaining POST data. Change your form to point to
kylewbanks.com/rest/posts/ (note the trailing slash), or set
APPEND_SLASH=False in your Django settings.
Its internal server error..check if there are any exceptions are getting thrown at server side.
It has nothing to do with your android code, the problem is at server.
You can use AsyncTask to run network/filesystem related operations.
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.
How would one go about sending data back to server, from an android application?
I've already tried using HttpPost and posted back to a RESTful WCF service, but I couldnt get that to work (I've already created a SO question about this, without finding the solution..) - No matter what I do I keep getting 405 Method not allowed or the 400 Bad Request.. :(
I'm not asking for full code example necessarily.. just a pointer in a direction, which can enable me to send data back to a server.
It is important that the user should not have to allow or dismiss the transfer.. it should happen under the covers, so to speak
Thanks in advance
Services is the way to go. REST (I recommend this one on Android), or SOAP based. There're loads of tutorials on getting an android app communicate a service, even with .net / wcf ones.
Tho you can always just open raw sockets and send data with some custom protocol.
Edit:
Here's the doInBackground part of my asynctask handling http post communication, maybe that'll help:
protected String doInBackground(String... req) {
Log.d(TAG, "Message to send: "+req[0]);
HttpPost p = new HttpPost(url);
try{
p.setEntity(new StringEntity(req[0], "UTF8"));
}catch(Exception e){
e.printStackTrace();
}
p.setHeader("Content-type", "application/json");
String response = "";
try{
HttpResponse resp = hc.execute(p, localContext);
InputStream is = resp.getEntity().getContent();
response = convertStreamToString(is);
Log.d("Response", "Response is " + response);
} catch (Exception e){
e.printStackTrace();
}
return response;
}
Let's say I want to perform a quick HTTP post to a website within my android app.
If I were to set up the http client and send the post all in the onCreate method of the main screen (inside the UI thread) just for testing purposes, what would I use to quickly see what the response is to the post?
I tried something quick and dirty below inside the onCreate method when the app first opens and nothing really happens, is there something more I need to do/obviously my toast idea is just bad...
HttpClient httpClient = new DefaultHttpClient();
HttpPost post = new HttpPost("http://forecast.weather.gov/zipcity.php?inputstring=04419");
HttpResponse httpResp;
try {
httpResp = httpClient.execute(post);
StatusLine status = httpResp.getStatusLine();
Toast.makeText(getApplicationContext(), (CharSequence) status, Toast.LENGTH_SHORT).show();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
LogCat is your friend. It gives you a view of what's happening inside the device. Then in your code add statements like this:
Log.i("MyClassName","HTTP response is " + httpResponseString);
It's common to create a class member variable called "TAG" and pass that as the first parameter, e.g.:
private String TAG = "MyClassName";
....
Log.i(TAG,"HTTP response is " + httpResponseString);
You can view LogCat using DDMS (Dalvik Debug Monitor), an IDE (Eclipse, IntelliJ IDEA, etc), and there's loads of LogCat apps in the Android Market that you can run on the phone.