I am working on REST API with "POST" type, I want to consume it by using WebView. I am using webView.postUrl() but I also need authentication header with my POST request which I am not able to do.
My code is given below, along with the information needed for my Rest api with POST type. Kindly guide me to solve this problem.
// Here is my block of code for using POST type Rest API
private static final String URL_STRING = "https://derxxxlist.net/uxxxco/Surxxxe/Membxxxhip/Axxxxin";
public void postData(WebView mWebView) throws IOException, ClientProtocolException {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("Username", "xxx#aaa.com"));
nameValuePairs.add(new BasicNameValuePair("Password", "qwerasdf"));
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(URL_STRING);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
String data = new BasicResponseHandler().handleResponse(response);
mWebView.loadData(data, "text/html", "utf-8");
}
// Here I am passing my webView in my above method:
new Thread(new Runnable() {
#Override
public void run() {
try {
postData(webView);
} catch (Exception e) {
e.printStackTrace();
}
}}).start();
What I want is to pass authentication header along with my above post API.
// My Authentication header
"authorization", "amx A93reRTUJHsxxxxxxxxxxCgps102ciuabc="
You can set the header of the Http request using setHeader
httppost.setHeader("Authorization", "amx A93reRTUJHsxxxxxxxxxxCgps102ciuabc=");
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'm trying to send data from my Android client as a POST request to my Web API Backend but it returns a 404 response code. Here's my code:
Backend:
[HttpPost]
[Route("api/postcomment")]
public IHttpActionResult PostComment(string comment, string email, string actid)
{
string status = CC.PostNewComment(comment, email, actid);
return Ok(status);
}
Android Code:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://MYWEBADDRESS.azure-mobile.net/api/postcomment");
String mobileServiceAppId = "AZURE_SERVICE_APP_ID";
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("comment", comment));
nameValuePairs.add(new BasicNameValuePair("email", currEmail));
nameValuePairs.add(new BasicNameValuePair("actid", currActID));
httppost.setHeader("Content-Type", "application/json");
httppost.setHeader("ACCEPT", "application/json");
httppost.setHeader("X-ZUMO-APPLICATION", mobileServiceAppId);
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairs);
httppost.setEntity(formEntity);
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
}
catch (Exception e) {
}
However this returns a 404 Response code to my Android Client. Is my Code incorrect? Please point out the mistakes :)
I fixed this by properly setting up my backend to accept the parameters sent by the android client. The problem was with my backend, not my client.
Here's my backend:
[Route("api/postcomment")]
public IHttpActionResult PostComment([FromBody] CommentViewModel model)
{
string comment = model.Comment;
//Do your processing
return Ok(return_something);
}
public class CommentViewModel
{
public string Comment { get; set; }
public string Email { get; set; }
public string Actid { get; set; }
}
I used the [FromBody] to force the method to read the request body and I used a model to get the values passed by the client. The method automatically gets the values from the request and sets them to the model making it very easy.
MAKE SURE that your android client is properly passing your parameters with a correct POST code.
I could make it work like this but there gotto be a better way. Any suggestion?
ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("token", session.getAccessToken()));
HttpParams httpParameters = new BasicHttpParams();
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpPost httpPost = new HttpPost(URL);
try {
httpPost.setEntity(new UrlEncodedFormEntity(params));
} catch (UnsupportedEncodingException e) {}
httpResponse = httpClient.execute(httpPost);
Web Api
[AcceptVerbs("GET", "POST")]
public IHttpActionResult FBToken()
{
string token = ((HttpContextWrapper)Request.Properties["MS_HttpContext"]).Request.Params["token"];
//some code
}
public IHttpActionResult FBToken(TokenRequest request)
{
//some code that uses request.Token
}
public class TokenRequest
{
public string Token { get; set; }
}
UPDATE
Oops, sorry thought I typed more. Anyways, here is the explanation. UrlEncodedFormEntity sets the content type of the request message to application/x-www-form-urlencoded. ASP.NET Web API has built-in media type formatter for de-serializing such content. By using a complex type (TokenRequest class), we ask Web API to bind the request body to this type and we get the token out using the Token property. This is better because we are not taking dependency on ASP.NET anywhere. This is easier to unit test and host-agnostic.
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'm trying to increase my knowledge to Android and trying to code a small app for my personal needs.
I'm trying to post data via the HTTP Post method on a test server.
The request is sent ok, but now, I'm trying to display the response, which is an HTML page with the dump of my request.
Here is an extract of my code, it is basically a few EditText fields, and button that sends the request.
The following code is the listener for that button.
validateButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://posttestserver.com/post.php?dump&html&dir=mydir&status_code=200");
try {
// Gathering data
String value01 = nb01Spinner.getSelectedItem().toString();
String value02 = nb02EditText.getText().toString();
String value03 = nb03EditText.getText().toString();
String value04 = nb04EditText.getText().toString();
// Add data to value pairs
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(04);
nameValuePairs.add(new BasicNameValuePair("test01", value01));
nameValuePairs.add(new BasicNameValuePair("test02", value02)); //
nameValuePairs.add(new BasicNameValuePair("test03", value03));
nameValuePairs.add(new BasicNameValuePair("test04", value04));
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
}
I'm not sure if I need to create another Activity or not... I suppose I also have to create a webview aswell, but I'm a bit lost. For now the "raw" HTML would be fine, but afterwards I will need to parse the data, and extract only the strings I need.
So I would need help (an a good and simple example !)
Thank you.
String ret = EntityUtils.toString(response.getEntity());
Maybe this will help?
Very simple approach is Take textview the way you have taken button widget. and what ever response you got set in the textview. you will be able to see the response. else use the Log to log your response in the logcat.
This is how you get the Http response :
byte[] buffer = new byte[1024];
httpclient = new DefaultHttpClient();
httppost = new HttpPost("http://www.rpc.booom.com");
postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("params","1"));
//.......
httppost.setEntity(new UrlEncodedFormEntity(postParameters));
HttpResponse response = httpclient.execute(httppost);
Log.w("Response ","Status line : "+ response.getStatusLine().toString());
buffer = EntityUtils.toString(response.getEntity()).getBytes();
I am using:
Log.d("log_response", response.getStatusLine().toString());