How to Send the Viewstate String, asp page values Via Httppost - android

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.

Related

POST data from Android to Web API returns 404

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.

Passing params from android to Web Api

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.

Cant authenticate my ACS token

Ive been trying to send messages to a azure service bus queue from android for a while and i just cant get it to work. This is the code i use for getting the ACS SWT:
private void getTokenFromACS() throws ClientProtocolException, IOException {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("https://servicebusnamespace-sb.accesscontrol.windows.net/WRAPv0.9/");
List<NameValuePair> parameters = new ArrayList<NameValuePair>(3);
parameters.add(new BasicNameValuePair("wrap_name", "name"));
parameters.add(new BasicNameValuePair("wrap_password", "password associated with the name"));
parameters.add(new BasicNameValuePair("wrap_scope", "Realm url"));
httppost.setEntity(new UrlEncodedFormEntity(parameters));
BasicHttpResponse httpResponse = null;
httpResponse = (BasicHttpResponse)httpclient.execute(httppost);
BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));
String[] tokenVariables = URLDecoder.decode(reader.readLine()).split("&wrap_access_token_expires_in=");
authorizationToken = tokenVariables[0];
}
This works fine, i get a string that has the wrap_access_token, issuer, audience, expiresOn and HMACSHA256.
What i try to do after that is to send a message with this token like this:
HttpClient requestClient = new DefaultHttpClient();
HttpPost post = new HttpPost("https://servicebusnamespace.servicebus.windows.net/queuename/messages");
post.addHeader("Authorization", "WRAP access_token=\""+authorizationToken+"\"");
Item item = new Item();
Date date = new Date();
item.setDate(date);
item.setId(1);
item.setRoadName("roadname");
item.setSpeed(60.0);
item.setLat(12.12);
item.setLng(12.12);
String json = new GsonBuilder().create().toJson(item, Item.class);
post.setEntity(new ByteArrayEntity(json.getBytes("UTF8")));
HttpResponse httpResponse = requestClient.execute(post);
This always result in my Token not being authenticated, i get the error message saying my token doesnt containt a signature or that it doesnt have the audience set. What could be wrong?
Note that this is on android =)
Thanks in advance!
Seems like you are missing some code. Your authorizationToken is currently something like this: "wrap_access_token=net.windows.servicebus.action%3dLis..."
The only thing you want is the part after the equal-sign.
I think this will do:
String[] tokenVariables = URLDecoder.decode(reader.readLine()).split("&wrap_access_token_expires_in=")[0].split("=");
authorizationToken = tokenVariables[1];

Post Parameters in Android Request

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

Android HTTPRequest Cycle

I am trying to send JSON to my server and retrieve a JSON in return as a result.
Like sending in username and password and getting back token and other content.
This is what i am doing for the HTTP Request for sending. How do i now retrieve back the content in the same request ?
HttpClient client = new DefaultHttpClient();
HttpPost request = new HttpPost("http://192.168.1.5/temp/test.php");
List<NameValuePair> value = new ArrayList<NameValuePair>();
value.add(new BasicNameValuePair("Name", jsonStr));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(value);
request.setEntity(entity);
HttpResponse res = client.execute(request);
String[] status_String=res.getStatusLine().toString().trim().split(" ");
//String hd=res.getFirstHeader("result").toString();
//System.out.println("Res=" + res);
Log.e("tag", ""+res.toString());
if(status_String[1].equals("200")){
isDataSent=true;
Let me add more in vvieux's answer:
res.getEntity().getContent()
will return you InputStream.
String returnData = EntityUtils.toString(res.getEntity());
You can use the HttpEntity
res.getEntity().getContent()

Categories

Resources