BasicNamesValuesPaire not working - java

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);

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

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

How to perform simple Http Post in android?

I'm new to http Post. All i want to do is to send that access_id=44321 as a url
like http://myurl.com/access_id=44321 will insert 44321 to access_id in the database how to perform this operation. Am I doing it Right ?
Thanks for the help !
public class IvrsPushService {
URL url;
HttpURLConnection conn;
Details details;
String userId;
void pushData() throws Exception {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://myurl.com/Acces/DEFAULT2.ASPX?");
try {
String accessid=Details.getAssetid();
String userid=Details.getUserid();
String datetime=Details.getDate()+"\""+Details.getTime();
String mobilenumber="9785";
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("access", accessid));
nameValuePairs.add(new BasicNameValuePair("user", userid));
nameValuePairs.add(new BasicNameValuePair("date", datetime));
nameValuePairs.add(new BasicNameValuePair("mobilenumber", mobilenumber));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
}
Http Client from Apache Commons is the way to go. It is already included in android. Here's a simple example of how to do HTTP Post using it.
public void postData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "12345"));
nameValuePairs.add(new BasicNameValuePair("stringdata", "Hi"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
Try this
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://myurl.com/");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("id", "44325"));
nameValuePairs.add(new BasicNameValuePair("first_name", "abc"));
nameValuePairs.add(new BasicNameValuePair("last_name", "xyz"));
nameValuePairs.add(new BasicNameValuePair("location", "lmn"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
} catch (Exception e) {
}

How to send a String array as basic name value pair as HTTPPOST?

I want to send a array as name value pair as httppost.My server accepts only array values.The following is my code snippet..
public String SearchWithType(String category_name, String[] type,int page_no) {
String url = "http://myURL";
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
String auth_token = Login.authentication_token;
String key = Login.key;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("authentication_token",
auth_token));
nameValuePairs.add(new BasicNameValuePair("key", key));
nameValuePairs.add(new BasicNameValuePair("category_name",
category_name));
int i = 0;
nameValuePairs.add(new BasicNameValuePair("type", type[i]));
nameValuePairs.add(new BasicNameValuePair("page", String.valueOf(page_no)));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
eu = EntityUtils.toString(entity).toString();
} catch (IOException ioe) {
String ex = ioe.toString();
return ex;
}
return eu;
}
I got the issue. Here's how:
try {
int i = 0;
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("authentication_token", auth_token));
nameValuePairs.add(new BasicNameValuePair("key", key));
nameValuePairs.add(new BasicNameValuePair("category_name", category_name));
nameValuePairs.add(new BasicNameValuePair("type", type[i]));
nameValuePairs.add(new BasicNameValuePair("page", String.valueOf(page_no)));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
eu = EntityUtils.toString(entity).toString();
} catch (Exception e) {
Log.e(TAG, e.toString());
}
All I had to do was initialize a loop:
for (int i = 0; i < type.length; i++) {
nameValuePairs.add(new BasicNameValuePair("type[]",type[i]));
}
nameValuePairs.add(new BasicNameValuePair("type", Arrays.toString(type)));
convert from array to string and then send using http post,again server side parse from String to array
json_array = [{param1:"param1Value", param2:"param2Value"}]
if you want send a json array with nameValuePairs you can send like this;
new BasicNameValuePairs("param[0][param1]","param1Value")
new BasicNameValuePairs("param[0][param2]","param2Value")

Android c2dm server simulator on emulator

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 "";
}

Categories