I am trying to send data to server using HTTPPOST. I have encoded username and password using BASE64.encodetoString(). But I am unable to post the data. There is no error but I am getting 400 or 404 response code every time. The code is successfully executed when done in Java, but it is not working as expected in android. Please help me.
Here is the code I am using:
public void getLoginInfo()
{
String user="xxxx#gmail.com";
String password="1234xyz";
// Creating HTTP client
HttpClient httpClient = new DefaultHttpClient();
// Creating HTTP Post
HttpPost httpPost = new HttpPost(url);
// String base64EncodedCredentials = "Basic " + Base64.encodeToString((user + ":" + password).getBytes(),0);
// Building post parameters
// key and value pair
byte[] data=(user+":"+password).getBytes();
String base64EncodedCredentials =Base64.encodeToString(data, Base64.DEFAULT);
String httpheader="Basic "+base64EncodedCredentials;
System.out.println("httpheader "+httpheader);
/* List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(2);
nameValuePair.add(new BasicNameValuePair("email", "nishanth.s#giwitservices.com"));
nameValuePair.add(new BasicNameValuePair("password","100006438166763hbsV1v0"));*/
// Url Encoding the POST parameters
// Making HTTP Request
// try {
try {
httpPost.setHeader("Authorization", httpheader);
//httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
HttpResponse response = httpClient.execute(httpPost);
System.out.println("response test "+response.toString());
System.out.println("response code "+response.getStatusLine().getStatusCode());
String the_string_response = convertResponseToString(response);
System.out.println("respones "+the_string_response);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Instead of using BASE64.DEFAULT, try to use BASE64.NO_WRAP. That would help you in resolving the issue.
Change this:
String base64EncodedCredentials =Base64.encodeToString(data, Base64.DEFAULT);
To this:
String base64EncodedCredentials =Base64.encodeToString(data, Base64.NO_WRAP|Base64.URL_SAFE);
Hope this helps.
Why don't you use this :
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("key_of_data", data));
HttpPost oHttpPost = new HttpPost(your_url);
oHttpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
Instead of using Base64 encoding
Related
I would like to send an http request to custom api.
I have the request details, and it is working using postman(http client).
Im trying to translate that request to android, using AsyncTask.
I couldnt managed to understand few things:
first, how to send the Bearer token that I have(oauth 2.0).
the second, how to send a jason body.
all the details about the request are in the following link:
https://web.postman.co/collections/7428863-ca5b907d-2752-4d4e-b8a8-29d5cd0dc098?version=latest&workspace=03f5fe5b-0ecd-43f8-8759-3aa868f4cb7f
my "DoInBackground" :
protected Void doInBackground(Void... voids) {
response = null;
Log.v("DoInBackground","entered");
//sending Data
if (valid) {
Log.v("ifvaild","entered");
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("https://dmyzcsu4e68qfgi56y7l2qu5ky40da2o.ui.nabu.casa/api/services/script/turn_on");
//httpPost.addHeader("Accept-Language", "he");
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
nameValuePair.add(new BasicNameValuePair("Authorization", "Bearer My Bearer"));
nameValuePair.add(new BasicNameValuePair("Content-Type", "application/json"));
nameValuePair.add(new BasicNameValuePair("script.turn_on", "script.gt1"));
Log.v("nameValue","entered");
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair, HTTP.UTF_8));
} catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
try {
response = httpClient.execute(httpPost);
Log.v("HttpClient","entered");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
this is not working, I get an authentication failure from the server
thanks for your help!
You need to add those pairs in the header. And add the body as entity.
// headers
httpPost.addHeader("Authorization", "Bearer My Bearer");
httpPost.addHeader("Content-Type", "application/json");
httpPost.addHeader("script.turn_on", "script.gt1");
// body
String bodyString = "{\"data\":1}"; // your json string
StringEntity bodyEntity = new StringEntity(bodyString);
httpPost.setEntity(bodyEntity);
Just a tip. Look into Retrofit2 library to do all of this.
I am new to android and I have a question about name value pairs that I am a little confused on. For example I am trying to post to the following example and get the response code using the endpoint:
/account/create/bank-id?ssn=SSN&name=NAME&email=EMAIL. I would edit the need to edit the following : bank-id , SSN , NAME, and EMAIL. at the moment. I am thinking along the lines of(so far no luck , no repsponse code are printing so I dont know what I am doing wrong at the moment, ty for any replies):
public void postData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://xx.xxx.xxx/account/create/");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
nameValuePairs.add(new BasicNameValuePair("bank-id", "12345"));
nameValuePairs.add(new BasicNameValuePair("ssn", "451"));
nameValuePairs.add(new BasicNameValuePair("name", "kitty"));
nameValuePairs.add(new BasicNameValuePair("name", "kitty"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
Log.d("Http Post Response:", response.toString());
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
I am trying to send a HTTP Post request in Android application.
This is what should I send:
This is what should I receive:
So, to conclude, I need to get cookies from response and response code should be 302.
I have a following Android code:
private static String makePostRequest() {
HttpClient httpClient = new DefaultHttpClient();
// replace with your url
HttpPost httpPost = new HttpPost("http://g1.botva.ru/login.php");
boolean flag = httpClient.getParams().isParameterTrue(ClientPNames.HANDLE_REDIRECTS);
httpPost.addHeader("Accept", "*/*");
httpPost.addHeader("Accept-Encoding", "gzip, deflate");
//httpPost.addHeader("Content-Length", "83");
httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
httpPost.addHeader("User-Agent", "runscope/0.1");
Header [] arr = httpPost.getAllHeaders();
String result123 = "";
//Post Data
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(5);
nameValuePair.add(new BasicNameValuePair("do_cmd", "login"));
nameValuePair.add(new BasicNameValuePair("server", "1"));
nameValuePair.add(new BasicNameValuePair("email", "avmalyutin#mail.ru"));
nameValuePair.add(new BasicNameValuePair("password", "avmalyutin1234"));
nameValuePair.add(new BasicNameValuePair("remember", "1"));
//Encoding POST data
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
} catch (UnsupportedEncodingException e) {
// log exception
e.printStackTrace();
}
//making POST request.
try {
HttpResponse response = httpClient.execute(httpPost);
String getCookie = response.getHeaders("Pragma").length + "";
result123 = response.getStatusLine().getStatusCode()+"";
// write response to log
Log.d("Http Post Response:", response.toString());
} catch (ClientProtocolException e) {
// Log exception
e.printStackTrace();
} catch (IOException e) {
// Log exception
e.printStackTrace();
}
return result123;
}
And I receive code 200. And there is only PHPSESSIONID in Cookies, but there are no other cookies.
You will need to instrument the DefaultHttpClient so that you can see the WIRE and the HEADERS.
Google log WIRE HEADERS for the client you are using. If you can not figure out the logging debug ( you may want to consider DIFF client )
Then, compare the 2 frameworks doing the post (your test harness VS android ) just narrowing the differences between what headers + POST BODY are being sent. As you get android to converge with your test harness, the android will produce the same 302 result you report getting from the test harness.
Adding function
con.setInstanceFollowRedirects(false);
resolve the problem and it stops redirecting. And also I received code 302 as desired.
Thanks everybody for help
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.
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.