Consume ASP.NET WebApi HTTP service in Android with HTTP POST - android

I have implemented ASP.NET WebApi and consumed in Android application with HTTPPOST. Parameter less methods are calling perfectly but method with parameters not working while it is working fine with Advanced Rest Client in Google Chrome also working perfectly with HTTP GET.
Caller Code in Android:
String url = "http://192.168.15.3/api/user"
HttpPost postMethod = new HttpPost(url);
postMethod.setHeader("Content-Type", "application/json; charset=utf-8");
postMethod.setHeader("Accept", "*/*");
postMethod.setHeader("Accept-Encoding", "gzip, deflate");
postMethod.setHeader("Accept-Language", "en-US,en;q=0.8");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("id", "1"));
DefaultHttpClient hc = new DefaultHttpClient();
HttpResponse response;
postMethod.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
response = hc.execute(postMethod);
HttpEntity entity = response.getEntity();
InputStream inStream = entity.getContent();
String result = convertStreamToString(inStream);
Log.e("Result: ", result);
Controller:
public class UserController : ApiController
{
UserCredentials[] users = new UserCredentials[]
{
new UserCredentials { User_ID = "1", User_Name = "testuser", Password = "test", First_Name = "Test", Last_Name = "User",
Email = "testuser#dummy.com", Phone ="123456789", Mobile = "123456789", User_Type = "user" },
new UserCredentials { User_ID = "2", User_Name = "testuser2", Password = "test", First_Name = "Test", Last_Name = "User",
Email = "testuser2#dummy.com", Phone ="123456789", Mobile = "123456789", User_Type = "user" }
};
[AcceptVerbs("POST")]
public IEnumerable<UserCredentials> GetAllUsers()
{
return users;
}
[AcceptVerbs("POST")]
public IHttpActionResult GetUser(string id)
{
var user = users.FirstOrDefault((p) => p.User_ID.Equals(id));
if (user == null)
{
return NotFound();
}
return Ok(user);
}
}
Error:
{"Message":"No HTTP resource was found that matches the request URI 'http://192.168.15.3/api/user'.","MessageDetail":"No action was found on the controller 'User' that matches the request."}

It is throwing an error because your controller does not have any matching httppost method. You are trying to post data to method which accepts GET request.
WebApi works on convention based method names. Your methods starts with "Get" so it will map requests in below manner :
Get All users - GET - /api/users
Get user by Id - GET - /api/users/id
So you can call them using HttpGet request and not POST.

Related

How can we follow/Unfollow instagram in android app?

When I use Follow/Unfollow API in instagram. I give me error like that.
Error:
{"meta":{"error_type":"OAuthPermissionsException","code":400,"error_message":"This client has not been approved to access this resource."}}
My Post method Call is here.
public static AllMessage postAction(String action, String UserID, String mAccessToken, DefaultHttpClient httpClient) {
AllMessage ReturnMessage = new AllMessage();
String url = String.format(RELATIONSHIP_URL, new Object[]{UserID, mAccessToken});
Log.v("log_tag", "FolURL " + url);
try {
HttpParams params = new BasicHttpParams();
params.setParameter("http.protocol.version", HttpVersion.HTTP_1_1);
params.setParameter("action=", action);
if (httpClient == null) {
httpClient = OpenHttpClientConnection();
}
HttpPost httpPost = new HttpPost(url);
List<NameValuePair> arrayList = new ArrayList(2);
arrayList.add(new BasicNameValuePair("action", action));
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", String.valueOf(arrayList));
UrlEncodedFormEntity ent = new UrlEncodedFormEntity(arrayList, "UTF-8");
httpPost.setEntity(ent);
String mHttpReturnedData = readInputStreamToString(httpClient.execute(httpPost).getEntity().getContent());
Log.v("log_tag", "Return " + mHttpReturnedData);
} catch (Exception e4) {
ReturnMessage.MessageType = "Unsupported Format";
ReturnMessage.MessageError = "Unsupported data format Error -1000";
ReturnMessage.ActionSucess = false;
ReturnMessage.ActionID = 0;
ReturnMessage.PrvAction = action;
}
return ReturnMessage;
}
Please help me for this code.
You need to first register your app to use the Instagram API
The link is here https://www.instagram.com/developer/endpoints/
Then you comunicate with the endpoint https://api.instagram.com/v1/tags/nofilter/media/recent?access_token=ACCESS_TOKEN
and make the proper calls.
Currently there is not an Android SDK made by them that I have heard of, but I'm pretty sure there has to be a 3rd party out there.
Hope it helps.

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.

HttpClient deprecated / Connect with PHP server - Android API 22

I am trying to make a login and register for an android app.
I have been having problems adjusting the code to API 22.
Although I know I have to use HttpURLConnection instead of HttpRequestParams etc., and have done that, I can't figure out how to adjust the code to incorporate the database server and my PHP files stored on there.
It's mostly this bit below that I can't figure out.
HttpClient client = new DefaultHttpClient(httpRequestParams);
HttpPost post = new HttpPost(SERVER_ADDRESS + "FetchUserData.php");
Can anyone help? Thanks in advance.
Here's the full code:
#Override
protected User doInBackground(Void... params) {
ContentValues contentValues = new ContentValues();
contentValues.put("username", user.username);
contentValues.put("password", user.password);
URL url = new URL(SERVER_ADDRESS);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setReadTimeout(CONNECTION_TIMEOUT);
HttpClient client = new DefaultHttpClient(httpRequestParams);
HttpPost post = new HttpPost(SERVER_ADDRESS + "FetchUserData.php");
User returnedUser = null;
try {
post.setEntity(new UrlEncodedFormEntity(dataToSend));
HttpResponse httpResponse = client.execute(post);
HttpEntity entity = httpResponse.getEntity();
String result = EntityUtils.toString(entity);
JSONObject jObject = new JSONObject(result);
if(jObject.length() == 0) {
returnedUser = null;
} else {
String mobile = jObject.getString("mobile");
String email = jObject.getString("email");
returnedUser = new User(mobile, email, user.mobile, user.email);
}
} catch(Exception e) {
e.printStackTrace();
}
return returnedUser;
}
first: It's already been answered
Sending Http request for Android 22+
second: I've made a class that meets your needs, which allow you to send request and receive response with one line of code (It's also explained in post above)
Here is the link for the my class:
HttpRequest

android Django rest API,authentication

A friend have a Rest API with Django, and Im trying to make and android app for it, but I having problems with the authentication.
First i get the CSRF token, just making a get call and taking the value.
public String getCFSRToken() throws Exception{
String csrftokenValue="";
httpClient.execute(new HttpGet(urlBasic));
cookieStore = httpClient.getCookieStore();
List <Cookie> cookies = cookieStore.getCookies();
for (Cookie cookie: cookies) {
Log.v("csrftoken",cookie.getName());
if ( cookie.getName().compareTo("csrftoken")==0) {
csrftokenValue = cookie.getValue();
}
}
return csrftokenValue;
}
Then I try to make the authentication:
public void login3() throws Exception{
String urlLogin ="/login";
String url = urlBasic+urlLogin;
String username = "jesus.m.martinez.garcia";
String password = "lolofree";
String userpass = username +":"+password;
HttpPost post = new HttpPost(url);
// List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
// nameValuePairs.add(new BasicNameValuePair("username", username));
// nameValuePairs.add(new BasicNameValuePair("password", password));
// post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
String basicAuth = "Basic " + new String(Base64.encode(userpass.getBytes(),Base64.NO_WRAP ));
post.addHeader("Authorization", basicAuth);
post.addHeader("X-CSRFToken", getCFSRToken());
HttpResponse response = httpClient.execute(post);
CookieStore as = httpClient.getCookieStore();
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line = "";
String pagina="";
while ((line = rd.readLine()) != null) {
pagina= pagina + "\n"+line;
}
System.out.println(pagina);
}
If I don't add the CSRF header I receive always a 403 Forbidden, so I suppose that part is correct, but when I try to do the login with the post (as you can see I have try without codification and basic), I always receive a 200 Ok, but I receive an HTML page for logging and I don't get the session cookie, that's what is killing me.
I asked my friend and he told me, he didn't modify the authentication of Django framework, so I suppose is not digest. Any idea what I am doing wrong?
Thank you in advance ;)

Android - Form based authentication

I need to upload some data on a site, using a POST request. I know to use HTTP client to execute a POST request
The problem is that in order to do this, you should authenticate first.
The site is a simple page prompting for a username and a password. I assume it stores a cookie in the browser and checks subsequent requests to see if I'm already authenticated.
But I don't have a concrete idea how to implement this on Android.
The client just gave me this:
URL to upload: http://xyz.com/?page=add
Credentials: admin/admin
Format of data:
$_POST = {
["Name"]=>string(255)
["Address"]=>string(255)
["ZIP"]=>string(50)
["City"]=>string(100)
["Phone"]=>string(50)
["Email"]=>string(50)
["Age"]=>int(11)
["Validation_Result"]=>string(255)
["Comment"]=>string(-)
}
$_FILES["Image"] = {
["name"]=>string "3D-graphics_3D_Triangles_006790_.jpg"
["type"]=>string "image/jpeg"
["tmp_name"]=>string "C:\Windows\Temp\php1362.tmp"
["error"]=>int(0)
["size"]=>int
}
And nothing else.
Could you please point me in the right direction how I would go about doing this?
How to do HTTP authentication in android?
Check out the top answer on this question. Very good explanation.
If you are doing the POST using HttpClient as the post you linked describes, you can add Basic Authentication by doing the following:
String username, password;
DefaultHttpClient client = new DefaultHttpClient();
UsernamePasswordCredentials creds = new UsernamePasswordCredentials(username, password);
client.getCredentialsProvider().setCredentials(AuthScope.ANY, creds);
HTH
I know this is a very old question, but this was the top search result I kept running into and I wanted to add another way that I managed to do this using CookieStore and HttpClient.
For my use case (Tomcat server configuration), I was hitting my base authenticated URL to get the cookie, POSTing my auth data to the form submission endpoint, and then using the cookie for subsequent calls. Here's the simplified piece of code that got it working for me:
String cookieUrl = "SOME_URL_THAT_WILL_PROVIDE_COOKIE";
String authenticateUrl = "URL_TO_POST_FORM_DATA";
String dataUrl = "AUTHENTICATED_URL_YOU_WANT_DATA_FROM";
final String userNameKey = "FORM_KEY_FOR_USERNAME";
final String userPassKey = "FORM_KEY_FOR_PASSWORD";
final String userName = "USER_NAME";
final String userPass = "USER_PASSWORD";
HttpClient client = new DefaultHttpClient();
CookieStore cookieStore = new BasicCookieStore();
HttpContext context = new BasicHttpContext();
context.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
String getUrl = cookieUrl;
HttpGet get = new HttpGet( getUrl );
HttpResponse getResponse = client.execute(get, context);
Log.d( "ConnectionTest", "GET # " + getUrl );
Log.d( "ConnectionTest", getResponse.getStatusLine().toString() );
List<NameValuePair> authDataList = new ArrayList<NameValuePair>();
authDataList.add( new NameValuePair() {
#Override
public String getName() {
return userNameKey;
}
#Override
public String getValue() {
return userName;
}
} );
authDataList.add( new NameValuePair() {
#Override
public String getName() {
return userPassKey;
}
#Override
public String getValue() {
return userPass;
}
} );
HttpEntity authEntity = new UrlEncodedFormEntity( authDataList );
String authPostUrl = authenticateUrl;
HttpPost authPost = new HttpPost( authPostUrl );
authPost.setEntity( authEntity );
HttpResponse authPostResponse = client.execute(authPost, context);
Log.d( "ConnectionTest", "POST # " + authPostUrl );
Log.d( "ConnectionTest", authPostResponse.getStatusLine().toString() );
String getUsersUrl = dataUrl;
HttpGet usersGet = new HttpGet( getUsersUrl );
HttpResponse usersGetResponse = client.execute(usersGet, context);
Log.d( "ConnectionTest", "GET # " + getUsersUrl );
Log.d( "ConnectionTest", usersGetResponse.getStatusLine().toString() );
Log.d( "ConnectionTest", EntityUtils.toString( usersGetResponse.getEntity() ) );

Categories

Resources