Android HTTP POST connection to file with response - android

How do I send the data to this PHP file below? I can establish the connection and send data, but can't receive the response. I need to send 3 parameters, the "op", Username and password.
switch ($_POST["op"]) {
// User Authentication.
case 1:
$UName = $_POST["UName"];
$UPass = $_POST["UPass"];
$UPass = md5($UPass);
//....Some code
// New user registration process.
case 2:
$UName = $_POST["UName"];
$UPass = $_POST["UPass"];
$UEmail = $_POST["UEmail"];
$UNick = $_POST["UNick"];
$UPass = md5($UPass);
//....Some code
}
My code so far:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://SomeUrl/login.php");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("1", "dan"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
response = httpclient.execute(httppost);
String responseBody = EntityUtils.toString(response.getEntity());
Log.d(TAG, ""+responseBody);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
What am I doing wrong?

Looking at your PHP code, at a bare minimum you need to specify an op parameter. Then depending on which op you're trying to carry out, make sure you specify the other needed parameters as well. For user authentication (op = 1):
nameValuePairs.add(new BasicNameValuePair("op", "1"));
nameValuePairs.add(new BasicNameValuePair("UName", "dan"));
nameValuePairs.add(new BasicNameValuePair("Pass", "somepass"));
On a side note, you should secure the PHP service with SSL, if you are using it to process sensitive user information.

Android HTTP POST should look like this:
HttpParams httpParams=new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 10000);
HttpConnectionParams.setSoTimeout(httpParams, 10000);
// Data to send
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("UName", "dan"));
nameValuePairs.add(new BasicNameValuePair("UPass", "password"));
nameValuePairs.add(new BasicNameValuePair("op", "1"));
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://SomeUrl/login.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
}
In your PHP code I would strongly recommend to use mysql_real_escape_string($_POST['UName']) otherwise it is easy to attack via SQL injection.
I would also recommend to use either SSL connection (HTTPS) or to send the password only hashed (MD5)

Related

Unable to connect to Salesforce using RestAPI: INVALID SESSION

Hi i am trying to connect to Salesforce with the Rest API and i want to retrieve sObjects..Implementing as below
void getsObjects() throws IOException {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("https://na14.salesforce.com/services/data/v24.0/sobjects");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("X-HostCommonName", "ap1.salesforce.com"));
nameValuePairs.add(new BasicNameValuePair("X-PrettyPrint", "1"));
nameValuePairs.add(new BasicNameValuePair("Host", "ap1.salesforce.com"));
nameValuePairs.add(new BasicNameValuePair("X-Target-URI", "https://ap1.salesforce.com"));
nameValuePairs.add(new BasicNameValuePair("Content-Type", "application/json"));
nameValuePairs.add(new BasicNameValuePair("Connection", "Keep-Alive"));
nameValuePairs.add(new BasicNameValuePair("Authorization", "00D90000000qUEp!AQQAQNnuPZqEX2oqAkeQLmvq.qsBfKIMa3GCJvE7atLv2Cjy94YZn5ezRH0bosXTFthnoMNt.WpDturXB1Ijxxxxxxxxxx"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httppost.setHeader("Content-Type","application/json");
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
String result = EntityUtils.toString(response.getEntity());
System.out.println("Final response"+result);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
even if i am passing the the Authorization key , it is giving INVALID SESSION error
12-11 14:50:18.108: W/DefaultRequestDirector(27014): Authentication error: Unable to respond to any of these challenges: {token=WWW-Authenticate: Token}
12-11 14:50:18.498: I/System.out(27014): Final response[{"errorCode":"INVALID_SESSION_ID","message":"Session expired or invalid"}]
I am trying to connect to it from 2 days but no luck, can someone point me right direction, how to make rest calls.
The Authorization header should take the form Authorization: Bearer {sessionId} whereas you have Authorization:{sessionId}
You nameValuePairs appears to contains http headers, but you're not creating headers, you're passing them to setEntity, which sets the http body payload, not the headers.
You're creating a bunch of standard headers (like Host) which don't align with the actual url, and these aren't needed anyway.
try something like
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("https://na14.salesforce.com/services/data/v24.0/sobjects");
httpPost.setHeader("Authorization" , "Bearer " + sessionId)
StringEntity entity = new StringEntity("someJson", "UTF-8");
entity.setCotnentType("application/json");
httpPost.setEntity(entity)
HttpResponse response = httpclient.execute(httppost);
String result = EntityUtils.toString(response.getEntity());
System.out.println("Final response"+result);
You might also want to checkout the Force.com Android SDK which has a bunch of helpers for accessing the API.

android send data as xml to server php

i have data is type String, and i want send this data to server as a xml.How do i do?Can you help me!
httpclient = new DefaultHttpClient();
httppost = new HttpPost("http://longvansolution.tk/login.php"); // make
// sure
// the
// url
// is
// correct.
// add your data
nameValuePairs = new ArrayList<NameValuePair>(2);
// Always use the same variable name for posting i.e the android
// side variable name and php side variable name should be
// similar,
nameValuePairs.add(new BasicNameValuePair("username",
txtusername.getText().toString().trim())); // $Edittext_value
// =
// $_POST['Edittext_value'];
nameValuePairs.add(new BasicNameValuePair("password",
txtpassword.getText().toString().trim()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
response = httpclient.execute(httppost);
Now i don't want use this way, i want send xml.
String url = "http://yourserver";
File file = new File(Environment.getExternalStorageDirectory(),
"yourfile");
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
InputStreamEntity reqEntity = new InputStreamEntity(
new FileInputStream(file), -1);
reqEntity.setContentType("binary/octet-stream");
reqEntity.setChunked(true); // Send in multiple parts if needed
httppost.setEntity(reqEntity);
HttpResponse response = httpclient.execute(httppost);
//Do something with response...
} catch (Exception e) {
// show error
}
possible duplicate of ttp://stackoverflow.com/questions/4126625/how-to-send-a-file-in-android-from-mobile-to-server-using-http

Android: How to send song file to server throught HttpPost along with other variables

I am to send a song file to server through HttpPost. Currently I am using this code to send data to server
HttpPost postRequest = new HttpPost();
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("email", Splash.pref.getString("userEmail", "")));
nameValuePairs.add(new BasicNameValuePair("password", Splash.pref.getString("userPassword", "")));
nameValuePairs.add(new BasicNameValuePair("name", etName.getText().toString()));
nameValuePairs.add(new BasicNameValuePair("title", ttfSongTitle.getText().toString()));
postRequest.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// construct a URI objectedsta
postRequest.setURI(new URI(serviceURL));
} catch (URISyntaxException e) {
Log.e("URISyntaxException", e.toString());
}
But to send song file to server I have find this code on net but having problems to integrate these both.
String url = "http://yourserver";
File file = new File(Environment.getExternalStorageDirectory(),
"yourfile");
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
InputStreamEntity reqEntity = new InputStreamEntity(
new FileInputStream(file), -1);
reqEntity.setContentType("binary/octet-stream");
reqEntity.setChunked(true); // Send in multiple parts if needed
httppost.setEntity(reqEntity);
HttpResponse response = httpclient.execute(httppost);
//Do something with response...
} catch (Exception e) {
// show error
}
Please help me so that I could integrate these both or some other solution, so that I could send Music file to server along with other authentication data.
I am sending data to server through secure restful service.
thanks.

send http post with header in android(This code works perfectly-I forgot to put the internet permission in manifest file that's why it didn't worked)

I know there are a few posts on this topic, but I just can figure out what I'm doing wrong.
I have to send by post some parameter to a php server that requires a login.
Here is the code:
DefaultHttpClient httpclient = new DefaultHttpClient();
String postUrl = "http://dev.demo.fr/Contacts/areaGet.php";
HttpHost targetHost = new HttpHost("dev.demo.fr", 80, "http");
httpclient.getCredentialsProvider().setCredentials(
new AuthScope(targetHost.getHostName(), targetHost.getPort()),
new UsernamePasswordCredentials("*****", "*****"));
HttpPost httppost = new HttpPost(postUrl);
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
nameValuePairs.add(new BasicNameValuePair("language_id", "1"));
nameValuePairs.add(new BasicNameValuePair("country_id", "1"));
nameValuePairs.add(new BasicNameValuePair("postal_code", "42830"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
response = httpclient.execute(targetHost, httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
System.out.println(response);
IMPORTANT: The username and password are uncoded in here:
httpclient.getCredentialsProvider().setCredentials(
new AuthScope(targetHost.getHostName(), targetHost.getPort()),
new UsernamePasswordCredentials("*****", "*****"));
The problem is that when I do this: System.out.println(response); it prints out null and I just don't know why!!!!
Thank you for your answers!!!
if you get response "null" from server it means your request is not successfully posted on server.

data security from android to web server?

I have android app . i should pass the data from android to web server with data security.Can any one suggest me to What are all the data security's can Provide.
You can send the data using HttpPost methos .
This is a simple example for 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", "AndDev is Cool!"));
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
}
}
Use Https , you should buy a SSL for your server first , and then Use https to send data.

Categories

Resources