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.
Related
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=");
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 have a code written in python which send's in the viewstate and the formvalues in this way
send('_VIEWSTATE=%2FwEPDwULLTE0MDM4Mz.........%2BhFiTeLDMyk...................&_EVENTVALIDATION=%2FwEWA....I%2.................mtK6HmOBny%2............NHcX5PO4r9oSpA&TextBox1='+payload+'&Button1=click\r\n')
where the dots stand for the rest of the string. Now i want to send this by httppost from android. I'm not able to understand how to translate the above code to httppost, i tried making the __VIEWSTATE,__EVENTVALIDATION as key's and the string's as value but that did not work. How can i send it ?? how do i send the above string as it is via httppost.
Do this:
private static final String DATA = "_VIEWSTATE=%2FwEPDwULLTE0MDM4Mz.........";
public String send() {
String result = null;
try {
HttpPost request = new HttpPost(new URI("<your POST uri>"));
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("data", DATA));
request.setEntity(new UrlEncodedFormEntity(params));
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(request);
BasicResponseHandler handler = new BasicResponseHandler();
result = handler.handleResponse(response);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
Call the send() method from a background Thread.
I am doing an Android application and I have a problem doing my request against my own server. I have made the server with Play Framework, and I get the parameters from a Json:
response.setContentTypeIfNotSet("application/json; charset=utf-8");
JsonParser jsonParser = new JsonParser();
JsonElement jsonElement = jsonParser.parse(getBody(request.body));
Long id =jsonElement.getAsJsonObject().get("id").getAsLong();
When I make my GET request against my server, all is ok. But when I make a POST request, my server return me an unknown error, something about there is a malformed JSON or that it is unable to find the element.
private ArrayList NameValuePair> params;
private ArrayList NameValuePair> headers;
...
case POST:
HttpPost postRequest = new HttpPost(host);
// Add headers
for(NameValuePair h : headers)
{
postRequest.addHeader(h.getName(), h.getValue());
}
if(!params.isEmpty())
{
postRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
}
executeRequest(postRequest, host);
break;
I have tried to do with the params of the request, but it was a failure:
if(!params.isEmpty())
{
HttpParams HttpParams = new BasicHttpParams();
for (NameValuePair param : params)
{
HttpParams.setParameter(param.getName(), param.getValue());
}
postRequest.setParams(HttpParams); }
And there is the different errors, depends on the request I make. All of them are 'play.exceptions.JavaExecutionException':
'com.google.gson.stream.MalformedJsonException'
'This is not a JSON Object'
'Expecting object found: "id"'
I wish somebody can help me.
Here is a simple way to send a HTTP Post.
HttpPost httppost = new HttpPost("Your URL here");
httppost.setEntity(new StringEntity(paramsJson));
httppost.addHeader("content-type", "application/json");
HttpResponse response = httpclient.execute(httppost);
You would be better off using the JSON String directly instead of parsing it here. Hope it helps
Try this,It may help u
public void executeHttpPost(String string) throws Exception
{
//This method for HttpConnection
try
{
HttpClient client = new DefaultHttpClient();
HttpPost request = new HttpPost("URL");
List<NameValuePair> value=new ArrayList<NameValuePair>();
value.add(new BasicNameValuePair("Name",string));
UrlEncodedFormEntity entity=new UrlEncodedFormEntity(value);
request.setEntity(entity);
client.execute(request);
System.out.println("after sending :"+request.toString());
}
catch(Exception e) {System.out.println("Exp="+e);
}
}
I want to send the JSON text {} to a web service and read the response. How can I do this from android? What are the steps such as creating request object, setting content headers, etc.
My code is here
public void postData(String result,JSONObject obj) {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpParams myParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(myParams, 10000);
HttpConnectionParams.setSoTimeout(myParams, 10000);
String json=obj.toString();
try {
HttpPost httppost = new HttpPost(result.toString());
StringEntity se = new StringEntity(obj.toString());
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
httppost.setEntity(se);
HttpResponse response = httpclient.execute(httppost);
String temp = EntityUtils.toString(response.getEntity());
Log.i("tag", temp);
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
}
what mistake i have done plz correct me because it shows me an bad request error
but when i do post in poster it shows me status as Successfull 200 ok
I do this with
httppost.setHeader("Content-type", "application/json");
Also, the new HttpPost() takes the web service URL as argument.
In the try catch loop, I did this:
HttpPost post = new HttpPost(
"https://www.placeyoururlhere.com");
post.setHeader(HTTP.CONTENT_TYPE,"application/json" );
List<NameValuePair> nameValuePairs = new
ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("json", json));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpClient client = new DefaultHttpClient();
HttpResponse resp = client.execute(post);
HttpEntity entity = resp.getEntity();
response = EntityUtils.toString(entity);
You can add your nameValurPairs according to how many fields you have.
Typically the JSON might become really huge, which I will then suggest gzipping it then sending, but if your JSON is fairly small and always the same size the above should work for you.
If it is a web service and not RestAPI call then, you can get the WSDL file from the server and use a SOAP Stub generator to do all the work of creating the Request objects and the networking code for you, for example WSClient++
If you wish to do it by yourself then things get a little tricky. Android doesn't come with SOAP library.
However, you can download 3rd party library here: http://code.google.com/p/ksoap2-android/
If you need help using it, you might find this thread helpful: How to call a .NET Webservice from Android using KSOAP2?
If its a REST-API Call like POST or GET to be more specific then its is very simple
Just pass a JSON Formatted String object in you function and use org.json package to parse the response string for you.
Hope this helps.