Android Upload image and phone number to server using OkHttp - android

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

Related

Sending something to a server - Updating android code

I would like to send a file to a server. Currently the code I use includes deprecated classes. How can I update the code to be uptodate?
protected String doInBackground(String... params) {
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), params[0]);
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(server);
InputStreamEntity reqEntity = new InputStreamEntity(new FileInputStream(file), -1);
reqEntity.setContentType("binary/octet-stream");
reqEntity.setChunked(true); // Send in multiple parts if needed
httppost.setEntity(reqEntity);
HttpResponse response = httpclient.execute(httppost);
//Do something with response...
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
I suggest you to use this library : retrofit
http://square.github.io/retrofit/
I use it on my project right now and it helps me a lot with my http requests.
Moreover the documentation is really good.

How to Upload Large Video FIle on server?

How to Upload Large Video FIle on server?
I want up to 50 to 60mb video File on Server but I dont know how its possible. I could not Upload up to 15mb video file on server. Please have any solution Then let me know.
public static String postRequestvideo_test(String url, byte[] video,
byte[] image, List data) {
String result = "";
Log.i("video_upload", video + "");
try {
HttpPost httpPost = new HttpPost(url);
// StringEntity se;
// se = new StringEntity(data, HTTP.UTF_8);
// httpPost.setEntity(new UrlEncodedFormEntity(data));
httpPost.setEntity(new UrlEncodedFormEntity(data, "UTF-8"));
MultipartEntity mpEntity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
mpEntity.addPart("video_thumbnail", new ByteArrayBody(image,
"imagename" + ".jpeg"));
mpEntity.addPart("video",
new ByteArrayBody(video, "hyman" + ".mp4"));
mpEntity.addPart("user_key", new StringBody("user_key_test"));
mpEntity.addPart("video_name", new StringBody("video_name_test"));
mpEntity.addPart("video_duration", new StringBody(
"video_duration_test"));
mpEntity.addPart("video_thumbnail_extn", new StringBody(
"video_thumbnail_extn_test"));
httpPost.setEntity(mpEntity);
HttpParams httpParameters = new BasicHttpParams();
int timeoutConnection = 90000000;
HttpConnectionParams.setConnectionTimeout(httpParameters,
timeoutConnection);
int timeoutSocket = 90000000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
BasicHttpResponse httpResponse = (BasicHttpResponse) httpClient
.execute(httpPost);
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
result = EntityUtils.toString(entity);
result = result.trim();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
return "-333" + e.toString();
}
return result;
}
// Old Answer, please CHECK BELOW FOR NEW ANSWER
The problem you're having is probably trying to load the entire video (or for that matter any large file) in the memory at once, since the app has a maximum limited memory allowed, if you exceed that, it will cause the application to crash and give you Out of Memory exception.
What you need to do is open a connection and set it to "Keep-Alive", then open a FileInputStream for reading your video, and start reading and sending as chunks (1-4 MB is probably a good size) until all the file bytes are sent. That way you ensure the stream is sending the data while you're not exceeding your allowed memory limit for your app.
// New Answer
Please note that the above is an old answer, right now I only use MultipartEntity (org.apache.http.entity.mime.MultipartEntityBuilder) and it takes care of any file size on its own.
mpEntity.addPart(Constant.VIDEO, new FileBody(file,
"video/mp4"));
I just put it and it's done.

how to post image byte[] value to database in spring mvc

Hi guys I am trying to post image to db.Here I am posting an image from android client to DB.Spring MVC REST web services is the mid layer.can you please suggest me how to post image byte[] value to db from android client. Thanks in advance for your valuable suggestions.
you can use MultipartEntity
public static HttpResponse sendImage(byte[] image) {
HttpResponse responsePOST = null;
try {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(postURL+"user_profile");
post.setHeader("Accept", "application/json");
ByteArrayBody bab = new ByteArrayBody(image, firstname+".png");
MultipartEntity reqEntity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("user_profile[image_attributes[attachment]]", bab);
post.setEntity(reqEntity);
responsePOST = client.execute(post);
} catch (Exception e) {
e.printStackTrace();
}
return responsePOST;
}

Sending Video using HTTP Post Multipart entity

What I want I want to send a video from my SDcard to a server. I also want to send some parameters/value with it.
I have tried I have tried the following code:
public String SendToServer(String aUrl,File aFile)
{
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(aUrl);
try
{
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
entity.addPart("file", new FileBody(aFile));
entity.addPart("video[title]", new StringBody("testVideo"));
entity.addPart("video[type]", new StringBody("1"));
httpPost.setEntity(entity);
HttpContext localContext = new BasicHttpContext();
// Bind custom cookie store to the local context
localContext.setAttribute(ClientContext.COOKIE_STORE, Globals.sessionCookie);
HttpResponse response = httpClient.execute(httpPost, localContext);
HttpEntity resEntity = response.getEntity();
String Response = "";
if (response != null)
{
Response = EntityUtils.toString(resEntity);
}
return Response;
}
catch (IOException e)
{
e.printStackTrace();
}
return "Exception";
}
What is the problem When I run this code, I get stuck at this line
HttpResponse response = httpClient.execute(httpPost, localContext);
I get no exception, no response nothing at all. Can anyone please guide me, what is the problem in here?
The above code in my question was perfect, but I had the network problem. My device was connected to a hotspot(Connectify Software). When I connected to the original network, this code worked perfect.
I recommend you people to never trust a hotspot for this kind of functionality.
try using this way if want to send as content or esle I will upload the project by tonight
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
InputStreamEntity reqEntity = new InputStreamEntity(new FileInputStream(filePath), -1);
reqEntity.setContentType("binary/octet-stream");
reqEntity.setChunked(true); // Send in multiple parts if needed
httppost.setEntity(reqEntity);
HttpResponse response = httpclient.execute(httppost);

FaceDetection onLine API in 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........

Categories

Resources