IOException on HTTP post request - android

I am creating a login form using Account Manageraccount manager and HTTP task for webservices. when i enter the username and password it gives me IOException, I have added the INTERNET PERMISSION and all the account related permission. If anyone knows any github example which uses account manager and webservices please share the url.please help.this is the code
`
public void userSignUp(String name, String email, String pass, String authType, final SignUPHandler handler) {
HttpPost localHttpPost = new HttpPost(ApiURL.USERSIGNIN);
JSONObject json_user = new JSONObject();
try {
json_user.put("email", email);
json_user.put("password", pass);
StringEntity se = new StringEntity(json_user.toString());
localHttpPost.setEntity(se);
if ((this.currentTask != null) && (this.currentTask.getStatus() != AsyncTask.Status.FINISHED))
this.currentTask.cancel(true);
this.currentTask = new HttpTask(ApiURL.HTTP_LOGIN_HOST, new HttpResponseHandler() {
public void handleException(Exception paramException) {
Log.e("Exceptionssssssss:", "" + paramException);
handler.handleException(paramException);
}
public void handleResponse(JSONObject json)
throws IOException {
Log.d("response", "" + json);
handler.handleResponse(json);
}
});
this.currentTask.execute(new HttpUriRequest[]{localHttpPost});
} catch (Exception localException) {
Log.d("Exception ID", "" + localException.getMessage());
}
}`

Related

Facebook Graph API not returning null for cover photo

I want to pick users' cover photo for use in an Android app. I have not taken any additional approvals from Facebook other than the open-public profile access.
Here is the code I am using right now, please tell me where I am going wrong. Currently, it is returning a null value.
String URL = "https://graph.facebook.com/" + THE_USER_ID + "?fields=cover&access_token=" + Utility.mFacebook.getAccessToken();
String finalCoverPhoto;
try {
HttpClient hc = new DefaultHttpClient();
HttpGet get = new HttpGet(URL);
HttpResponse rp = hc.execute(get);
if (rp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
String result = EntityUtils.toString(rp.getEntity());
JSONObject JODetails = new JSONObject(result);
if (JODetails.has("cover")) {
String getInitialCover = JODetails.getString("cover");
if (getInitialCover.equals("null")) {
finalCoverPhoto = null;
} else {
JSONObject JOCover = JODetails.optJSONObject("cover");
if (JOCover.has("source")) {
finalCoverPhoto = JOCover.getString("source");
} else {
finalCoverPhoto = null;
}
}
} else {
finalCoverPhoto = null;
}
} catch (Exception e) {
// TODO: handle exception
}
Here is my code which i have used for fetching Cover Photo.
Use GraphRequest instead of DefaultHttpClient.
Bundle params = new Bundle();
params.putString("fields", "cover");
new GraphRequest(token,
"me",
params,
HttpMethod.GET,
new GraphRequest.Callback() {
#Override
public void onCompleted(GraphResponse response) {
if (response != null) {
try {
JSONObject data = response.getJSONObject();
if (data.has("cover")) {
String coverPicUrl = data.getJSONObject("cover").getString("source");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}).executeAsync();
Check if your are getting value of coverPicUrl.
I hope it helps!

Access token validation from Google, Google+ Sign-in Android

I want to fetch an access-token from Google and then send it to my server as a JSON object*.
On server I want to validate the access token and then store essential user information.
My server is written in Node.js. How to do that?
#Override
public void onConnected(Bundle connectionHint) {
Log.v(TAG, "Connected. Yay!");
findViewById(R.id.sign_in_button).setVisibility(View.INVISIBLE);
AsyncTask<Void, Void, String> task = new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... params) {
String code;
Bundle appActivities = new Bundle();
appActivities.putString(GoogleAuthUtil.KEY_REQUEST_VISIBLE_ACTIVITIES,
"http://schemas.google.com/AddActivity");
String scopes = "oauth2:" + Scopes.PLUS_LOGIN + " " + Scopes.PLUS_ME;
try {
code = GoogleAuthUtil.getToken(
AuthenticationActivity.this, // Context context
mPlusClient.getAccountName(), // String accountName
scopes, // String scope
appActivities // Bundle bundle
);
} catch (UserRecoverableAuthException e) {
// Recover
code = null;
//System.out.println(e.printStackTrace());
AuthenticationActivity.this.startActivityForResult(e.getIntent(), REQUEST_AUTHORIZATION);
} catch (Exception e) {
throw new RuntimeException();
}
return code;
}
#Override
protected void onPostExecute(String token) {
/* if(token!=null)
{
Log.i(TAG, "Access token retrieved:" + token);
//SharedPreference = getApplicationContext().getSharedPreferences("TokenPreference", 0);
//editor = SharedPreference.edit();
editor.putString("access_token",token);
editor.commit();
} */
try
{
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://gumbox1.cloudapp.net:3000");
JSONObject data = new JSONObject();
data.put("data", token);
HttpEntity entity = new StringEntity(data.toString());
BufferedReader reader = new BufferedReader(new InputStreamReader(client.execute(post).getEntity().getContent()));
String response = reader.readLine();
Log.e("response", response);
}
catch(Exception e)
{ Log.e("",e.toString());
}
}
};
task.execute();
}
You need to pass auth token to https://www.googleapis.com/oauth2/v1/userinfo?access_token= url. It will return the JSON data for user information.
You should do like
private static final String USER_INFO_URL = "https://www.googleapis.com/oauth2/v1/userinfo?access_token=";
URL url = new URL(USER_INFO_URL + code);
con = (HttpURLConnection) url.openConnection();
InputStream is = con.getInputStream();
// Now convert into String and then into Json

Rest with Android 4.0

Folks, I have an web service running on my PC, recently I changed my application from 2.2. for 4.0, and after that I cant connect to my WS anymore.
I'm looking for answers and found nothing.
My application refers the URL like thishttp://10.0.2.2:8080 ... But it dosn't work.
Heres my code:
private static final String URL_WS = "http://10.0.2.2:8080/WS_TaxiShare/)";
public String login(String email, String password) throws Exception {
String[] resposta = new WSClient().get(URL_WS + "login/login/?login="+ email +"&password="+ password);
String saida = resposta[1];
if (resposta[0].equals("200")) {
return saida;
} else {
return saida;
}
}
Now the WSClient
public class WSClient {
public final String[] get(String url) {
String[] result = new String[2];
HttpGet httpget = new HttpGet(url);
HttpResponse response;
try {
Log.i("Get taxi", "Url -> " + url);
response = HttpClientSingleton.getHttpClientInstace().execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null) {
result[0] = String.valueOf(response.getStatusLine().getStatusCode());
InputStream instream = entity.getContent();
result[1] = toString(instream);
instream.close();
Log.i("get", "Result from post JsonPost : " + result[0] + " : " + result[1]);
}
} catch (Exception e) {
Log.i("Exception no get WS taxi", "Exception ->" + e);
result[0] = "0";
result[1] = "Falha de rede!";
}
return result;
}
Well, i can solve my problem. Android 4.0 (I dont know when it begin), you cant call webservices on the main thread. And all you need to do is create a async method to do what you need in a separeated thread.
Here is my method
private class loginTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String response = "";
try {
WSTaxiShare ws = new WSTaxiShare();
response = ws.login(login, password);
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
#Override
protected void onPostExecute(String strJson) {
}
and here is the call button
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
loginTask task = new loginTask();
task.execute(new String[] { "" });
}
});
}

Consuming Web Service Android 4.0

Folks, I have an web service running on my PC, recently I changed my application from 2.2. for 4.0, and after that I cant connect to my WS anymore.
I'm looking for answers and found nothing.
My application refers the URL like this http://10.0.2.2:8080 ... But it dosn't work.
Heres my code:
private static final String URL_WS = "[this is not a link]http://10.0.2.2:8080/WS_TaxiShare/)";
public String login(String email, String password) throws Exception {
String[] resposta = new WSClient().get(URL_WS + "login/login/?login="+ email +"&password="+ password);
String saida = resposta[1];
if (resposta[0].equals("200")) {
return saida;
} else {
return saida;
}
}
Now the WSClient
public class WSClient {
public final String[] get(String url) {
String[] result = new String[2];
HttpGet httpget = new HttpGet(url);
HttpResponse response;
try {
Log.i("Get taxi", "Url -> " + url);
response = HttpClientSingleton.getHttpClientInstace().execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null) {
result[0] = String.valueOf(response.getStatusLine().getStatusCode());
InputStream instream = entity.getContent();
result[1] = toString(instream);
instream.close();
Log.i("get", "Result from post JsonPost : " + result[0] + " : " + result[1]);
}
} catch (Exception e) {
Log.i("Exception no get WS taxi", "Exception ->" + e);
result[0] = "0";
result[1] = "Falha de rede!";
}
return result;
}
Someone can help me?
PS: My WS running on Glassfish
Well, i can solve my problem. Android 4.0 (I dont know when it begin), you cant call webservices on the main thread. And all you need to do is create a async method to do what you need in a separeated thread.
Here is my method
private class loginTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String response = "";
try {
//Pegando o email e a senha da tela
String login = loginLogin.getText().toString();
String password = loginSenha.getText().toString();
WSTaxiShare ws = new WSTaxiShare();
Log.i("inciando login taxi", "Login -> " + login + " Senha -> " + password);
response = ws.login(login, password);
Log.i("String resposta taxi", response + "");
} catch (Exception e) {
Log.i("Exception Login taxi", e + "");
gerarToast("Não Foi possível logar");
e.printStackTrace();
}
return response;
}
#Override
protected void onPostExecute(String strJson) {
try {
...
} catch (JSONException e) {
...
}
}
}
And here is the call button:
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
loginTask task = new loginTask();
task.execute(new String[] { "" });
}
});

Which URL to be used for app engine client in cloud computing?

I am using cloud computing in my app for push notification. I have a problem in client auth token. I am using the following for authenticating client login token
public class AppEngineClient {
private static final String TAG = "AppEngineClient";
public static final String BASE_URL = " <Don't know which URL to use here>";
public static final String AUTH_URL = BASE_URL + "/_ah/login";
public static final String AUTH_TOKEN_TYPE = "ah";
public final Context mContext;
public final String mAccountName;
public AppEngineClient(Context context, String accountName) {
this.mContext = context;
this.mAccountName = accountName;
}
public HttpResponse makeRequest(String urlPath, List<NameValuePair> params) throws Exception {
HttpResponse res = makeRequestNoRetry(urlPath, params, false);
if (res.getStatusLine().getStatusCode() == 500) {
res = makeRequestNoRetry(urlPath, params, true);
}
return res;
}
public HttpResponse makeRequestNoRetry(String urlPath, List<NameValuePair> params, boolean newToken)
throws Exception {
// Get auth token for account
Account account = new Account(mAccountName, "com.google");
String authToken = getAuthToken(mContext, account);
if (authToken == null) throw new PendingAuthException(mAccountName);
if (newToken) { // invalidate the cached token
AccountManager accountManager = AccountManager.get(mContext);
accountManager.invalidateAuthToken(account.type, authToken);
authToken = getAuthToken(mContext, account);
}
// Get ACSID cookie
DefaultHttpClient client = new DefaultHttpClient();
String continueURL = BASE_URL;
URI uri = new URI(AUTH_URL + "?continue=" +
URLEncoder.encode(continueURL, "UTF-8") +
"&auth=" + authToken);
HttpGet method = new HttpGet(uri);
final HttpParams getParams = new BasicHttpParams();
HttpClientParams.setRedirecting(getParams, false); // continue is not used
method.setParams(getParams);
HttpResponse res = client.execute(method);
Header[] headers = res.getHeaders("Set-Cookie");
if (res.getStatusLine().getStatusCode() != 302 ||
headers.length == 0) {
return res;
}
String ascidCookie = null;
for (Header header: headers) {
if (header.getValue().indexOf("ACSID=") >=0) {
// let's parse it
String value = header.getValue();
String[] pairs = value.split(";");
ascidCookie = pairs[0];
}
}
// Make POST request
uri = new URI(BASE_URL + urlPath);
HttpPost post = new HttpPost(uri);
UrlEncodedFormEntity entity =
new UrlEncodedFormEntity(params, "UTF-8");
post.setEntity(entity);
post.setHeader("Cookie", ascidCookie);
post.setHeader("X-Same-Domain", "1"); // XSRF
res = client.execute(post);
return res;
}
public String getAuthToken(Context context, Account account) {
String authToken = null;
AccountManager accountManager = AccountManager.get(context);
try {
AccountManagerFuture<Bundle> future =
accountManager.getAuthToken (account, AUTH_TOKEN_TYPE, false, null, null);
Bundle bundle = future.getResult();
authToken = bundle.getString(AccountManager.KEY_AUTHTOKEN);
// User will be asked for "App Engine" permission.
if (authToken == null) {
// No auth token - will need to ask permission from user.
Intent intent = new Intent("com.google.ctp.AUTH_PERMISSION");
intent.putExtra("AccountManagerBundle", bundle);
context.sendBroadcast(intent);
}
} catch (OperationCanceledException e) {
Log.w(TAG, e.getMessage());
} catch (AuthenticatorException e) {
Log.w(TAG, e.getMessage());
} catch (IOException e) {
Log.w(TAG, e.getMessage());
}
return authToken;
}
public class PendingAuthException extends Exception {
private static final long serialVersionUID = 1L;
public PendingAuthException(String message) {
super(message);
}
}
}
This is the class I am using for user authentication through app engine client through Chrome to phone example of cloud computing but I don't understand while using this class which BASE_URL, I have to give in this class. Please, tell me which URL to use and what to be done on server side if URL is from server side.
Thanks in advance
The pattern for AppEngine base URLs is either
http://<<appname>>.appspot.com or https://<<appname>>.appspot.com

Categories

Resources