FaceDetection onLine API in Android - android

Can any one tell me which is the best way for onLine FaceDetection in Android. Is there any API for the same? If yes, then how we can implement that? Please suggest me for the right solution.
Thanks in advance.

You can use Face.com API for the same.
It returns JSON response after facedetection.
First you have to register on Face.com, it will generate your API ID and secret Key.
Then you have to upload your image on the face.com server as:
Bitmap img = BitmapFactory.decodeFile(paramFile.getPath());
System.out.println("The Width="+img.getWidth()+" & Height:"+img.getHeight());
String str = "";
if (this.httpclient == null)
{
BasicHttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 10000);
HttpConnectionParams.setSoTimeout(httpParams, 10000);
this.httpclient = new DefaultHttpClient(httpParams);
}
this.httpclient.getParams().setParameter("http.protocol.version", HttpVersion.HTTP_1_1);
HttpPost post = new HttpPost("http://api.face.com/faces/detect.json");
HttpClientParams.setCookiePolicy(post.getParams(), "compatibility");
MultipartEntity multiPart = new MultipartEntity();
multiPart.addPart("upload", new FileBody(paramFile, "image/jpeg"));
multiPart.addPart("api_key", new StringBody("5438f02c1f03bbd229e209abfc811cfb"));
multiPart.addPart("api_secret", new StringBody("6892f15e9721ad0e720a82f8a7d214c9"));
multiPart.addPart("f_upload", new StringBody(paramFile.getName()));
multiPart.addPart("detector", new StringBody("Aggressive"));
multiPart.addPart("attributes", new StringBody("all"));
post.setEntity(multiPart);
response = this.httpclient.execute(post);
HttpEntity responseEntity = response.getEntity();
if (responseEntity != null)
str = EntityUtils.toString(responseEntity);
return (String)str;
This will return a response string as JSON, if the face is detected it gives all information about face if not then doen't give any information. You have to parse that JSON and get the result and enjoy........

Related

Android Upload image and phone number to server using OkHttp

In my application I have been using DefaultHttpClient for uploading images to the server but it takes too much time to give response when server is down. I have put my code here. And AFIK DefaultHttpClient is going to be deprecated, so I want to use OkHttp instead of DefaultHttpClient. So please help me to change my code to use OkHttp for uploading images. I have searched a lot but don't know how to make the changes. please help me....
public String upLoadImg(byte[] image,String name,String phone,String imei,String randomId){
String mResponseData = null;
try{
mHttpClient = new DefaultHttpClient();
mHttpPost = new HttpPost(Constants.BASE_URL +"user/asset");
mHttpPost.setHeader("Accept", "application/json");
mHttpPost.setHeader("mobile-number", phone);
mHttpPost.setHeader("uid", imei);
MultipartEntity reqEntity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
if(image !=null) {
ByteArrayBody bab = new ByteArrayBody(image, name);
reqEntity.addPart("file", bab);
}
mHttpPost.setEntity(reqEntity);
Log.e("TAG", "***** mHttpClient is going to execute ");
HttpParams httpParameters = mHttpClient.getParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 2 * 1000);
HttpConnectionParams.setSoTimeout(httpParameters, 2 * 1000);
mHttpResponse = mHttpClient.execute(mHttpPost);
HttpEntity resEntity = null;
if(mHttpResponse!=null)
resEntity = mHttpResponse.getEntity();
if(resEntity!=null)
mResponseData = EntityUtils.toString(resEntity).trim();
}catch(HttpHostConnectException e){
Log.e("TAG","Exception cannot connect to server while sending images ",e);
return null;
}catch(Exception e){
Log.e("TAG","Exception occured while sending images ",e);
return null;
}
return mResponseData;
}
I had overcame this issue by replacing DefaultHttpClient with Okhttpclient.
As far as i know DefaultHttpClient is deprecated in latest android versions.So i had switched to OkHttpClient and then all issues fixed

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

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];

Change the name of a file right before uploaded to server

I need to upload an image to my server under a specific name, but ideally, I would like to still keep image stored on the device under the original file name. This is what I tried:
myImageFile.renameTo(new File("mobileimage.jpg"));
but when the file was uploaded to the server, it did not appear to have my new name. Here is the full code that uploads the image to the server:
DefaultHttpClient mHttpClient;
HttpParams params = new BasicHttpParams();
params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
mHttpClient = new DefaultHttpClient(params);
try {
myImageFile.renameTo(new File("mobileimage.jpg"));
HttpPost httppost = new HttpPost("http://mywebsite/mobile/image");
MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
multipartEntity.addPart("userID", new StringBody(Constants.userID));
multipartEntity.addPart("uniqueMobileID", new StringBody(Constants.uniqueMobileID));
multipartEntity.addPart("userfile", new FileBody(myImageFile));
httppost.setEntity(multipartEntity);
HttpResponse response = mHttpClient.execute(httppost);
String responseBody = EntityUtils.toString(response.getEntity());
Log.d(TAG, "response: " + responseBody);
return responseBody;
} catch (Exception e) {
Log.d(TAG, e.getMessage());
}
How can I change the file name?
Use the constructor of FileBody that takes the fileName as an argument
Try using the other implementation of addPart when attaching the file, so that you may add the filename field to the HTTP request. Something like this:
FormBodyPart userFile = new FormBodyPart("userfile", new FileBody(myImageFile));
userFile.addField("filename","NEWNAMEOFILE.jpg");
multipartEntity.addPart(userFile);
Is it possible renameTo() is returning false? You should check your return values, especially with renameTo().

Android and authenticated HttpPut with JSON body

How do you do write an HttpPut request with authentication on Android?
(I'm trying to work around using HttpURLConnection, which seems to serious have bugs (at least in Android 2.2) but GET works fine. I'd like to send a JSON representation of an array, and I have correct credentials already set using PasswordAuthentication.)
First you need to have an authentication token. And then just add this line.
httpGet.setHeader("Authorization", "Bearer " + yourToken);
Here's one general solution.
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, this.CONNECT_TIMEOUT);
HttpConnectionParams.setSoTimeout(httpParameters, this.CONNECT_TIMEOUT);
DefaultHttpClient client = new DefaultHttpClient(httpParameters);
// Retrieve user credentials.
SharedPreferences settings = context.getSharedPreferences("LOGIN", 0);
String loginNameString = settings.getString("login_name", null);
String passwordString = settings.getString("password", null);
UsernamePasswordCredentials credentials =
new UsernamePasswordCredentials(loginNameString, passwordString);
AuthScope authScope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT);
client.getCredentialsProvider().setCredentials(authScope,
credentials);
HttpPut put = new HttpPut(UPLOAD_URL);
try
{
put.setEntity(new StringEntity(responseJSONArray.toString(),
SERVER_PREFERRED_ENCODING));
put.addHeader("Content-Type", "application/json");
put.addHeader("Accept", "application/json");
HttpResponse response = client.execute(put);
// 200 type response.
if (response.getStatusLine().getStatusCode() >= HttpStatus.SC_OK &&
response.getStatusLine().getStatusCode() < HttpStatus.SC_MULTIPLE_CHOICES)
{
// Handle OK response etc........
}
}
catch (Exception e)
{
}

Categories

Resources