Android c2dm server simulator on emulator - java

I am following android c2dm example from following link:
http://www.vogella.de/articles/AndroidCloudToDeviceMessaging/article.html
I have implemented the client side successfully and have got my registration id. but i am having some issues in server end using the same example actually the issue is in getAuthentification method and i am getting following exception at HttpResponse response = client.execute(post).
java.net.UnknownHostException: www.google.com
Following is my code:
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(
"https://www.google.com/accounts/ClientLogin");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("Email","you....#gmail.com"));
nameValuePairs.add(new BasicNameValuePair("Passwd","*********"));
nameValuePairs.add(new BasicNameValuePair("accountType", "GOOGLE"));
nameValuePairs.add(new BasicNameValuePair("source",
"Google-cURL-Example"));
nameValuePairs.add(new BasicNameValuePair("service", "ac2dm"));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = client.execute(post);
BufferedReader rd = new BufferedReader(new InputStreamReader(
response.getEntity().getContent()));
String line = "";
while ((line = rd.readLine()) != null) {
Log.e("HttpResponse", line);
if (line.startsWith("Auth=")) {
Editor edit = prefManager.edit();
edit.putString(AUTH, line.substring(5));
edit.commit();
String s = prefManager.getString(AUTH, "n/a");
Toast.makeText(this, s, Toast.LENGTH_LONG).show();
}
}
} catch (IOException e) {
e.printStackTrace();
}
Please help me? Your help would be highly appreciable. Thanks,

I had this exact same issue last week. When the C2DM servers return a 302 Moved (www.google.com) what they ACTUALLY mean is the authentication failed. The problem is almost certainly your authentication code, so re-check the code you're using to get the auth code from the ClientLogin API. Note that the HTTP response contains a bunch of information, not just the auth code, so you do need to parse it correctly (that was my mistake).
public static String getClientLoginAuthToken(String email, String password) {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("https://www.google.com/accounts/ClientLogin");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("Email", email));
nameValuePairs.add(new BasicNameValuePair("Passwd", password));
nameValuePairs.add(new BasicNameValuePair("accountType", "GOOGLE"));
nameValuePairs.add(new BasicNameValuePair("source","Google-cURL-Example"));
nameValuePairs.add(new BasicNameValuePair("service", "ac2dm"));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = client.execute(post);
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line = "";
while ((line = rd.readLine()) != null) {
if (line.startsWith("Auth=")) {
return line.substring(5);
}
}
} catch (IOException e) {
e.printStackTrace();
}
Log.e(TAG, "Failed to get C2DM auth code");
return "";
}

Related

INSERT query works in SQL but doesn't work from android app

I'm trying to send an INSERT query to my SQL DataBase but it doesn't work and no error is appearing but the query works if I send it from phpMyAdmin.
here is my PHP code :
if ($_POST['func'] == 2) {
$dbca = taskdb();
$dbca->set_charset("utf8");
$mobileUser = $_POST['phone'];
$fullnameUser = $_POST['fullname'];
$usernameUser = $_POST['username'];
$sql = "INSERT INTO users (UserPhone, Username, UserFullname) VALUES (?,?,?)";
$result = $dbca->prepare($sql);
$result->bind_param("sss", $mobileUser,$fullnameUser,$usernameUser);
echo json_encode(array('profileUser' => 'DONE'));
}
and here is my java(client) code which is inside an AsyncT doInBacground:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.2.26/MyProject/fetchData.php");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("func", "2"));
nameValuePairs.add(new BasicNameValuePair("phone", Login.user_phone));
nameValuePairs.add(new BasicNameValuePair("fullname", fullname.getText().toString()));
nameValuePairs.add(new BasicNameValuePair("username", username.getText().toString()));
Log.e("mainToPost", "mainToPost" + nameValuePairs.toString());
UrlEncodedFormEntity form;
form = new UrlEncodedFormEntity(nameValuePairs,"UTF-8");
httppost.setEntity(form);
HttpResponse response = httpclient.execute(httppost);
InputStream inputStream = response.getEntity().getContent();
Signup.InputStreamToStringExample str = new Signup.InputStreamToStringExample();
responseSignup = str.getStringFromInputStream(inputStream);
Log.e("response", "response -----" + responseSignup);
jsonresponse = new JSONObject(responseSignup);
} catch (Exception e) {
e.printStackTrace();
}
return null;
I'm getting "DONE" as the response in client but no row would be inserted into my DataBase.
any help will be much appreciated.
add
$result->execute();
after
$result->bind_param("sss", $mobileUser,$fullnameUser,$usernameUser);
in php file

Sending Https Request But Not Getting Response

I am sending Https request to mysql server but not getting the response while performing the same task on localhost it is working. I have no experience using Https, please give me solution and explain difference between Http and Https request sending to mysql server, hope someone help me thanks in advance.
This is my code
protected String doInBackground(String... params) {
String emailSend = params[0];
String tokenSend = params[1];
String deviceIdSend = params[2];
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("email", emailSend));
nameValuePairs.add(new BasicNameValuePair("token", tokenSend));
nameValuePairs.add(new BasicNameValuePair("deviceId", deviceIdSend));
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("https://xyz/xyz/xyz.php");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
result = sb.toString();
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
return "success";
}
#Override
protected void onPostExecute(String resultN) {
super.onPostExecute(resultN);
String s = resultN.trim();
//dialog.dismiss();
if (s.equalsIgnoreCase("success")) {
if (result.contains("Pass")) {

BasicNamesValuesPaire not working

I need to pass variable from android to php.
my file is on localhost, and the connection between android and the file is ok except the php dont get the variables i send from android.
I tried with $_get, $_POST
I tried to add .tostring method after my int variable
doesn't work
Java
protected String doInBackground(String... param) {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<>();
nameValuePairs.add(new BasicNameValuePair("p1", param[0].toString()));
nameValuePairs.add(new BasicNameValuePair("p2", param[1].toString()));
nameValuePairs.add(new BasicNameValuePair("p3", param[2].toString()));
nameValuePairs.add(new BasicNameValuePair("p4", param[3].toString()));
nameValuePairs.add(new BasicNameValuePair("p5", param[4].toString()));
nameValuePairs.add(new BasicNameValuePair("age", param[6].toString()));
nameValuePairs.add(new BasicNameValuePair("sexe", param[5]));
try {
HttpClient client = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2/AppBdd.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
client.execute(httppost);
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
return null;
}
}
My php file appBdd.php :
require_once ("rees.php");
$pdo = PdoGsb::getPdoGsb();
$sexe = $_REQUEST['sexe'];
$age = $_REQUEST['age'];
$max = $_REQUEST['p1'];
$max2 = $_REQUEST['p2'];
$max3 = $_REQUEST['p3'];
$max4 = $_REQUEST['p4'];
$max5 = $_REQUEST['p5'];
$pdo->setClient($sexe, $age, $max, $max2, $max3, $max4, $max5);

org.apache.http.client.ClientProtocolException appears when HttpClient executes

I want to send to server some data via POST-request. My code:
protected Void doInBackground(Void... arg)
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost post = new HttpPost("https://money.yandex.ru/oauth/authorize");
post.addHeader("Host", "m.sp-money.yandex.ru");
post.addHeader("Content-Type", "application/x-www-form-urlencoded");
post.addHeader("Content-Length", "154");
//data back from server
String responseBackFromServer = "";
try
{
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("client_id", "51"));
pairs.add(new BasicNameValuePair("response_type", "code"));
pairs.add(new BasicNameValuePair("redirect_uri", "https://vk.com/"));
pairs.add(new BasicNameValuePair("scope", "account-info"));
post.setEntity(new UrlEncodedFormEntity(pairs));
HttpResponse server_response = httpclient.execute(post);//!!!exception is appearing here!!!
responseBackFromServer = EntityUtils.toString(server_response.getEntity());
}
catch (ClientProtocolException e)
{
e.printStackTrace();
Log.d(LOG_TAG, "" + e);
}
}
But on "HttpResponse server_response = httpclient.execute(post);" string ClientProtocolException appears. How can I fix it?
Try removing all the addHeader statements. The framework should add them for you.
See here for an example: https://hc.apache.org/httpcomponents-client-4.3.x/quickstart.html

Programmatically logging in from WebView

In my Android application I'm using a web view to access some web mapping data provided by a server. The server requires some HTTP form based authentication to allow access to those data. Due to the fact that the site doesn't have a mobile version, displaying the login page (or any other pages) looks pretty bad . Unfortunately the site is hardly into my reach so I've thought of the following approach:
use a native user interface to collect the username and password
thought a Http post send those information to the server
after the response is received get the cookies the server is sending
set the cookies to the the web view
try to finally access the desired data
For now I'm just trying to pass the login phase.
Is this a viable solution , or is just plain wrong and I should try something else ?
For completeness I post the code below
A. The authentication part
private String authenticate() throws Exception
{
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://mySite/login_form");
HttpResponse response = null;
BufferedReader in = null;
String resultContent = null;
try
{
// Add data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("came_from", ""));
nameValuePairs.add(new BasicNameValuePair("form.submitted", "1"));
nameValuePairs.add(new BasicNameValuePair("js_enabled", "0"));
nameValuePairs.add(new BasicNameValuePair("cookies_enabled", ""));
nameValuePairs.add(new BasicNameValuePair("login_name", ""));
nameValuePairs.add(new BasicNameValuePair("pwd_empty", "0"));
nameValuePairs.add(new BasicNameValuePair("name", "username"));
nameValuePairs.add(new BasicNameValuePair("password", "password"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Create a local instance of cookie store
CookieStore cookieStore = new BasicCookieStore();
// Create local HTTP context
HttpContext localContext = new BasicHttpContext();
// Bind custom cookie store to the local context
localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
// Execute HTTP Post Request
response = httpclient.execute(httppost,localContext);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null)
{
sb.append(line + NL);
}
in.close();
resultContent = sb.toString();
Log.i("mytag","result :"+resultContent);
cookies = new java.util.ArrayList();
cookies = cookieStore.getCookies();
}
catch (ClientProtocolException e)
{
Log.i("mytag","Client protocol exception");
}
catch (IOException e)
{
Log.i("mytag","IOException");
}
catch(Exception e)
{
Log.i("mytag","Exception");
Log.i("mytag",e.toString());
}
return resultContent;
}
B. Setting the cookies and loading the desired page
private void init()
{
CookieSyncManager.createInstance(this);
CookieManager cookieMan= CookieManager.getInstance();
cookieMan.setAcceptCookie(true);
cookies = StartupActivity.listAfter;
if(cookies != null)
{
for (int i = 0; i<cookies.size(); i++)
{
Cookie cookie = cookies.get(i);
cookieMan.setCookie("cookie.getDomain()",cookie.getValue());
}
}
CookieSyncManager.getInstance().sync();
webView = (WebView)findViewById(R.id.web_view);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setBuiltInZoomControls(true);
webView.setWebViewClient(new HelloWebViewClient());
}
protected void onResume()
{
super.onResume();
// test if the we logged in
webView.loadUrl("mySite/myDesiredFeature");
}
The results of loading that page is that the login_page form is displayed
1) Try first to make HttpGet request, to get cookies, then perform HttpPost. I think this way you should not add cookies manually.
Use one HttpClient to do this.
2) Instead of
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null)
{
sb.append(line + NL);
}
in.close();
resultContent = sb.toString();
use
EntityUtils.toString(response.getEntity()).

Categories