how to post string data in byte format to server? - android

I want to send a string data, "" , in bytes format to server in android app. I uses the HttpClient but i think its not the right way, please help me how to do this?
in case of .net , i want similar code in java.
string boundary = Guid.NewGuid().ToString();
HttpWebRequest request = HttpWebRequest.Create(url)
as HttpWebRequest;
request.Method = "POST";
//request.ContentType = "application/json";
request.PreAuthenticate = true;
byte[] fulldata = Encoding.UTF8.GetBytes(data);
request.ContentLength = fulldata.Length;
using (Stream sw = request.GetRequestStream())
{
sw.Write(fulldata, 0, fulldata.Length);
}

First convert your string data to byte and by using ByteArrayEntity send data to server in byte format.
try like this
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.1.1/xxx");
HttpResponse response;
HttpParams hp = new BasicHttpParams();
//use ByteArrayEntity to send string data in byteformat
ByteArrayEntity byteEntity = new ByteArrayEntity(byte_data);
httppost.setEntity(byteEntity);
response = httpclient.execute(httppost);

Related

how to post a base64 string to a server?

i'm tring to post base64 string to server and it won't post maybe because the sting is too long and i got this messege A connection to "server" was leaked. Did you forget to close a response body?
this is my code
try {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
selectedImageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
selectedImageBitmap.recycle();
byte[] byteFormat = stream.toByteArray();
stream.close();
stream = null;
// get the base 64 string
String imgString = Base64.encodeToString(byteFormat, Base64.DEFAULT);
selectedImageBitmap=null;
System.gc();
byteFormat=null;
System.gc();
Log.d("image",""+ imgString);
Log.d("urlnya", "" + LOGIN_URL);
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost post = new HttpPost(LOGIN_URL);
HttpClient httpclientpost = new DefaultHttpClient();
final HttpResponse responsepost = httpclientpost.execute(post);
Log.d("respon post", "" + responsepost.getStatusLine().getStatusCode());
post.addHeader("Content-Type", "application/json");
JSONObject json = new JSONObject();
json.put("user_id", 6);
json.put("status", status_id);
json.put("keterangan", ket);
json.put("foto", imgString);
Log.d("image",""+ encodedImage);
StringEntity entity = new StringEntity(json.toString());
post.setEntity(entity);
HttpResponse responsepost2 = httpClient.execute(post);
Log.d("respon post2", "" + responsepost2.getStatusLine().getStatusCode());
// checking log for json response
Log.d("processing ", json.toString());
} catch (JSONException | IOException e) {
e.printStackTrace();
}
i've tried to post base64 which is with this long
/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEB
AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/2wBDAQEBAQEBAQEBAQEBAQEBAQEBAQEB
AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/wAARCAQ4B4ADASIA
AhEBAxEB/8QAHwAAAAYDAQEBAAAAAAAAAAAABAUGBwgJAgMKAAEL/8QAfBAAAQMCBQIDBAcGAwQE
AAI7AQIDEQQFAAYSITEHQRNRYQgicYEJFDKRobHwFSNCwdHhM1LxFiRDYgoXcpIlNFNjgsLSGCZE
VJOistQZNUVVVmRzg5XT4ic3RmV0doSUwyg2OGZ1d6Oks8TW8khXZ4WHprS2xYaWpafV/8QAHgEA
AAcBAQEBAAAAAAAAAAAAAQIDBAUGBwAICQr/xABhEQABAwIEBAQEBAUDAgICASUBAgMRBCEABRIx
BkFRYRMicYEHkaHwFDKxwSNC0eHxCBVSFmIkMxclQ2NyCRg0RIKSojVGU1RVc5PSJkVWZISUwjZm
dIOVsnWFpLO0xNP/2gAMAwEAAhEDEQA/AOY5bKTqJO49PMR8N+eSZA4wVVlGFAqEbjmADIjnCibS
N1KA3AA4gk7D7u0/D0wGfZBKjGxH+sDj79/wxmoWTZRvAjlIIB+d8ZAw8rUkK6C/TblB5/e+EhHh
AJO5JPf5+Xl8MGDYlsdpHY/29MankpDiZGw1fzHb/ScDWEoWlCRBnYwdwfjufKcJOkggiCAL/t9M
SKlAwY5XIk9dv1548g/w7naZPyH6P4Y2jnkj1wITSTunadtyd/wx8NI8gnUklPYgz+JHnHOEPETM
2B2JJ5W5W7YT1J6j548EagJAUOJMennjQu3trMhWkzIhKfUxPPfApKVBQkKEzyDvt6/lgQhIO6uB
zv8ArtjpIukiDFhJHLr1+ntgiVlJsZAsO4+9pmMEpoikmFAnyj8v1xjYKcgbkQJ539T2woWWkKiU
9+fnET8P1GDJFG24mAjzBPHn3jBDUQJj/PzwY1Mb+/pb05CfsQi/DUD72w85H4f3xsTsQB6RP88K
1y1EiUNg+W5mCR6RxgKbUqTLZ+9X9MGS+hXa07jt6dccKptYuI25xeB17nb6csFKDI3jaB+v18hg
xo16zG593cE9hInv5cYwXbahJENqE8kFR+XHw7YFMspYEwQvTHM/HbtG0zGDyhUn6z6d49ux7SC1
IUAUmenP129t/wC+DBlJKhA228h3GFFTEpWB3gCfh5YTbCyNye+2w33H4/0weMOiQoniDMeUGfL+
W/xw1dBNuXL6TP3++GTid4G230n1wsaFQ9wHkkfjPPx/1woWUpWdIJEem/fvx2GEhQVKDp1HaRB2
439f9O8CMKVl2BKDKvP039f192I1xrST1O17fcW7jvOIV9CrzvtJm9/ToesfueNpgpSBulQJ4G3J
EidvTCxthT4IBABgbcgz345O388Ji3pDhQTuTJI2gcCYgxhYUrICEBA321fKPIdzOGbnL3+/piGq
VwQgjaDB9j9b/SOeFTaG9Sx6oJnYdzzyduMODTUxhCvUeXp6/P44QltStCxED3SOfie2HLt+l1DQ
I/iTOwB7H9enzwrTpClAc567SRf09RyOIZwysn72wurKzqSAIkhvtHZPPP674eKw0klnggSZMdtP
z/nhu7PTJIGhPujw5M9vd7/CP54ebL9IoBk6dhO0yeUeY49efXFny2m8wO8wetyUg8uff5Ww0Ugk
XERz6ff3fC4tNAHAkgiPEjcD17fHn0w5Vqth1pIIiByE/wDMO0flgmsNFLYJb/4p843keX3wcPFZ
7P4i2h4UyEjYgd+OPId+/pONAyylUSAE3kbg9RF+REyN474aqsDPOw5X+vr9Ma7LalLca3EaiP4e
fdgx8/PjD52qnKWo22SgcDsgev8ATBRZLK214RLJkA8wd/d/5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pBUGWiZJMydMnjYzwd8L205d
pacNrUoKSCSD4TfEggRpmNsPdZciUCW0F6klZbSNlgnVKht7mxgjAyuyGpOp2npVhtIEfvFT37BH
qOPynG05L8NGaUpqqr+JMLLfnDhA0KtNk7ECOvPHzU+LX+rjiDih6py7h5K6VpMtipSlgsQA4g6Q
kL1kBaTOoSB+XlhH0jVGtBShKUEAAlLSUnYJ76R+jgpu9pWttxaFSJUoAwNiOD5wNogeXG+FSLPV
0ygCytIiDGomRt5enbAj6vKdC0EmNwR+G4+H3bbY0RthimZDDFMlpIEahq1D8ouTsPS/1x43zLNM
0zl41Wb1btW/qkatIAMJEhKQlMAAbiNvXEe7pRuU7g1EfY33HET29MJGuAW2obECQdXeZkHbfj4c
4kxXWBh8SWAokEbERwQNwk8/y+GEdWZKQtKopoO8e/EzP/Jxhi4FImElXcX2j9Zj9JwlTvIbgFJE
ETO02FrAbDpHS0YiLmnLzNcl1cJSstL4ba2KlJI3IkydhxA5xGLNlgeo1AoXsdAI1BMEgR9kb7Tv
8sWN3vIr6g4E0hMIUBClHckRuEd9vh6YjpnTJFa2R/uDhPuQdJUP4ef3f8vLDdDhtIi1gbbx1m5I
mMXDKcwbJSkqAiBBIjl1M2/UHviCVQ0Q4tB/xArmQRtO08/r5Yzp6dXc8/P7UbfyHw9cOTmHLTtP
UvKVSrbWFpB2IiVK7FHn/bywTUdmcW5JZUQkp7EbyP8Al/Pv6YVU6TAmLR9+8X3mMXX8WktphUgB
IiRew6/Pc/vjVQ0igkGdikeU8nj4nCkp6UmJ9P8AKex/Pvg3Ysz2lOhg7Acg+vMJ+7v+ODJiiUgg
FEKBgg8yBsDInnDVTsbA/L079f264YrrAVQJJi4F+Ynnz++xMqimNMDm
or maybe longer i dont know exacly. but it won't post because it prosses too much string (maybe)
please help how can i post base64 to server. thank you

Android FileBody equivalent encoding in iOS

We have some code posting an image and some other data as part of a Multipart in a POST request. In Android is working just fine, but I can't seem to make it work on iOS, where I keep getting a 500 Internal Server Error. The working Android code looks like
String uploadURL = "http://someServer.com/upload";
String imageToUploadPath = "imgFilePath";// path de la imagen a subir
String userId = "123";
String token = "abcd";
HttpClient httpClient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(uploadURL);
File f = new File(imageToUploadPath);
FileBody fileBody = new FileBody(f);
MultipartEntity reqEntity = new MultipartEntity();
Charset chars = Charset.forName("ISO-8859-1");
reqEntity.addPart("id", new StringBody(userId, chars));
reqEntity.addPart("token", new StringBody(token, chars));
reqEntity.addPart("image", fileBody);
httppost.setEntity(reqEntity);
HttpResponse response = httpClient.execute(httppost);
My iOS attempt using AFNetworking is as follows
uploadURLStr = #"http://someServer.com/upload";
NSString *token = #"abcd";
NSString *userID = #"123";
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
NSMutableSet *supportedContentTypes = [manager.responseSerializer.acceptableContentTypes mutableCopy];
supportedContentTypes addObject:#"text/html"];
manager.responseSerializer.acceptableContentTypes = supportedContentTypes;
NSURLSessionTask *task = [manager POST:uploadURLStr
parameters:nil
constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
NSDictionary *tokenHeaders = #{#"Content-Disposition": #"form-data",
#"name": #"token",
#"Content-Type": #"text/plain",
#"charset": #"ISO-8859-1",
#"Content-Transfer-Encoding": #"8bit"
};
[formData appendPartWithHeaders:tokenHeaders body:[token dataUsingEncoding:NSISOLatin1StringEncoding]];
NSMutableDictionary *userIDHeaders = [tokenHeaders mutableCopy];
[userIDHeaders setObject:#"id" forKey:#"name"];
[formData appendPartWithHeaders:[userIDHeaders copy] body:[userID dataUsingEncoding:NSISOLatin1StringEncoding]];
NSDictionary *imgHeaders = #{#"Content-Disposition": #"form-data",
#"name": #"image",
#"filename": fileName,
#"Content-Type": #"application/octet-stream",
#"Content-Transfer-Encoding": #"binary"
};
[formData appendPartWithHeaders:imgHeaders
body:[imgData base64EncodedDataWithOptions:0]];
}
progress:^(NSProgress *uploadProgress) {
NSLog(#"progress: %.2f", uploadProgress.fractionCompleted);
}
success:^(NSURLSessionTask *task, id responseObject) {
NSLog(#"responseObject = %#", responseObject);
} failure:^(NSURLSessionTask *task, NSError *error) {
[self showUploadError];
NSLog(#"error = %#", error);
}];
Headers for each part we managed to log it from the Android app so we replicated it -for instance, I was sending the image with a Content-Type of image/jpeg and Android sends it as application/octet-stream- I assume that the image data is not being encoded as in Android. I have tried with base64 encoding as it's in the code now -tried different options other than 0-, just leaving the NSData returned by UIImageJPEG representation but I can't hit the nail. Any help is appreciated.

How to send Image file with other parameters using HttpGet method in android?

I need to upload image file on Server using HttpGet Method.Please help me out.
Thanks
use http post request ...convert image to byte array and then send it to server
InputStream is = this.getAssets().open("image.png");
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest =
new HttpPost("http://webserver.com/doSomething.do");
byte[] data = IOUtils.toByteArray(is);
InputStreamBody isb = new InputStreamBody(new
ByteArrayInputStream(data), "uploadedFile");
StringBody sb1 = new StringBody("some text goes here");
StringBody sb2 = new StringBody("some text goes here too");
MultipartEntity multipartContent = new MultipartEntity();
multipartContent.addPart("uploadedFile", isb);
multipartContent.addPart("one", sb1);
multipartContent.addPart("two", sb2);
postRequest.setEntity(multipartContent);
HttpResponse response =httpClient.execute(postRequest);
response.getEntity().getContent().close();
As already hinted by Nitesh, in order to upload image file you should use a Post request and submit your file as binary.
Please refer below link in SO for more details:
How do I send a file in Android from a mobile device to server using http?
Try this
String _URL =https://194.1.3.9:7721/request?image_byte=iamge _inbyte;
HttpClient client = getHttpClient();
HttpPost request = new HttpPost(_URL);
HttpResponse response = client.execute(request);
private static HttpClient getHttpClient() {
if (mHttpClient == null) {
mHttpClient = new DefaultHttpClient();
final HttpParams params = mHttpClient.getParams();
HttpConnectionParams.setConnectionTimeout(params, HTTP_TIMEOUT);
HttpConnectionParams.setSoTimeout(params, HTTP_TIMEOUT);
ConnManagerParams.setTimeout(params, HTTP_TIMEOUT);
}
return mHttpClient;
}

Sending an Image to a server to create Blob key in android

I want to send an image captured by camera to a server, which creates blob key. I am not getting how to send that image to the server. In which format is the image is sent?
I am trying to send parameters through HttpParams.
This is my code but the data is not going to server. What is the problem?
String name=tname.getText().toString();
String addr=taddr.getText().toString();
String age=tage.getText().toString();
String cnct=tcnct.getText().toString();
String gen=tgen.getText().toString();
String wtm=twtm.getText().toString();
ba1=Base64.encodeToString(imageform, 0);
Date d=new Date();
String date=d.toString();
InputStream i1;
String back="";
HttpParams p=new BasicHttpParams();
p.setParameter("vname",name);
p.setParameter("address", addr);
p.setParameter("age", age);
p.setParameter("contact", cnct);
p.setParameter("gender", gen);
p.setParameter("whomto", wtm);
p.setParameter("myFile", ba1);
try {
HttpClient httpclient = new DefaultHttpClient(p);
HttpPost res=new HttpPost(result);
HttpResponse response = httpclient.execute(res);
HttpEntity entity = response.getEntity();
i1 = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(i1,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
if ( reader.readLine() == null) {
Log.e("inside if","No data");
} else {
String line = reader.readLine();
i1.close();
back=sb.toString();
}
I am not getting any errors or exceptions.
You should make an MultipartPost and add the file to your MultipartEntity as follows :
multipartEntity.addPart("data", new FileBody(capturedImagePath));
You should have a look a this answer Multipart post with Android for a more detailed answer.
Encode the image, using Base64, to a String and send it using MultipartEntity.
In php retrieve the string an unpack it with base64_decode to the image.
Check this question:
https://stackoverflow.com/questions/10145417/android-send-image-through-http-post

How can I read a bytearray from an HttpResponse?

I'm making an http connection using following code:
HttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse response = client.execute(httpPost);
I want to read a bytearray from the response object.
How would I do that?
You can read the byte array directly with the method: EntityUtils.toByteArray
Example
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet("localhost:8080/myurl");
HttpResponse response = client.execute(get);
byte[] content = EntityUtils.toByteArray(response.getEntity());
You can use:
HttpResponse response = client.execute(httpPost);
String content = EntityUtils.toString(response.getEntity());
byte[] bytes = content.getBytes("UTF8");
You can replace the character encoding with one appropriate for the response.
I did something very similar to this, but it was a while ago.
Looking at my source code I used
HttpClient client = new DefaultHttpClient();
String url = "http://192.168.1.69:8888/sdroidmarshal";
HttpGet getRequest = new HttpGet(url);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String proto = client.execute(getRequest, responseHandler);
I'm pretty certain that the ResponseHandler is the key to this. My get request simply returned something I needed as a string, which was quite simple.
In the case of a bytearray you'll probably want to use an InputStream like so
ResponseHandler<InputStream> responseHandler = new BasicResponseHandler();
InputStream in = client.execute(getRequest, responseHandler);
After which just handle the InputStream as normal.
A bit of googling suggested you may also need to use HttpResponseHandler() rather than BasicResponseHandler() as in my example, I'd fiddle.
The full source code of my work is here, it might be helpful for you.
Kotlin Way
run this on async task on background thread otherwise it will through the error that network task is running on main thread
doAsync {
val client: HttpClient = DefaultHttpClient()
val get = HttpPost("*your url*")
get.setHeader("Authorization","Bearer "+Utils.token)
val response: HttpResponse = client.execute(get)
val content = EntityUtils.toByteArray(response.getEntity())
onComplete {
createPdf(content)
}
}

Categories

Resources