I'm trying to post some compressed data plus text to a perl program on a web server but cannot change the header from octet-stream to multipart/form-data.
My code is:-
HttpClient httpclient = new DefaultHttpClient();
String url = "http://webaddress/perl.pl";
HttpPost httppost = new HttpPost(url);
httppost.setHeader("Content-Type","multipart/form-data");
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
try {
entity.addPart("mtdata",new ByteArrayBody(data, file.getLastPathSegment()));
entity.addPart("email", new StringBody(strUserName));
entity.addPart("mtfilename", new StringBody(file.getLastPathSegment()));
httppost.setEntity(entity);
HttpResponse httpresponse = httpclient.execute(httppost);
HttpEntity resEntity = httpresponse.getEntity();
response = EntityUtils.toString(resEntity);
}
The raw data being received is :-
Buffer = --FfT4ZNRUCPw6yONkpSsXNkA3WA2l6fvy53
Content-Disposition: form-data; name="mtdata"; filename="filename"
Content-Type: application/octet-stream <<=== cannot change this
... Some binary data ...
What am I doing wrong?
In the end I found that the best way was to save it as a file and then post the file using MultipartEntity with a FileBody explicitly stating the Content-Type.
The code I used was:-
pairs.addPart("File", new FileBody(fout,"multipart/form-data"));
As an aside, I also found that I needed to use ZipOutputStream rather than GZIPOutputStream so that I could add the uncompressed file name.
Code for that was:-
data = bos.toByteArray();
OutputStream fos = new FileOutputStream(extStorageDirectory + newfilename);
ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(fos));
try {
ZipEntry entry = new ZipEntry(file.getLastPathSegment());
zos.putNextEntry(entry);
zos.write(data);
zos.closeEntry();
}
finally {
zos.close();
}
fos.close();
Try insert
httppost.addHeader("Content-Type", "multipart/form-data");
and remove
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
Related
I asked this question before but I don't get answer. I want to upload image from android application to django. this is my android code:
public void upload(String filepath) throws IOException{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(SoberRequest.UPLOAD_IMAGE_URL);
File file = new File(filepath);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
FileBody cbFile = new FileBody(file, "image/jpeg");
builder.addPart("image", cbFile);
HttpEntity mpEntity = builder.build();
httppost.setEntity(mpEntity);
httppost.setHeader("enctype", "multipart/form-data");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
...
}
and this is my djnago code to get image:
#csrf_exempt
def get_image(request):
if request.method == "POST":
destination_path = open("Images/filan.jpg", "wb+")
print(request.FILES)
image = request.FILES['image']
destination_path.write(image)
destination_path.close()
json_data = {"status": SUCCESSFUL}
return HttpResponse(json.dumps(json_data), mimetype=json_mimeType)
else:
json_data = {"status": ERROR}
return HttpResponse(json.dumps(json_data), mimetype=json_mimeType)
but when I print request.FILES , it is empty. but if I print request.body I see a field that name is "image" like this : b'--Z7unui4m0r4igQdqkvmj7DQ5rm46GmZDm\r\nContent-Disposition: form-data; name="image"\r\n\r\n\xff\xd.....". also if I set header in my android app like this :
httppost.addHeader("Content-type", "multipart/form-data")
I get another error in my django : "Invalid boundary in multipart: None"
what is problem ?
I want to upload image from android app to djnago. this is my android code to upload image:
public void upload(String filepath) throws IOException{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(SoberRequest.UPLOAD_IMAGE_URL);
File file = new File(filepath);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
FileBody cbFile = new FileBody(file, "image/jpeg");
builder.addPart("image", cbFile);
HttpEntity mpEntity = builder.build();
httppost.setEntity(mpEntity);
httppost.setHeader("enctype", "multipart/form-data");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
...
}
and this is my django code to get and save image:
#csrf_exempt
def get_image(request):
try:
if request.method == "POST":
destination_path = open("Images/filan.jpg", "wb+")
print(request.FILES)
image = request.FILES['image']
destination_path.write(image)
destination_path.close()
json_data = {"status": SUCCESSFUL}
return HttpResponse(json.dumps(json_data), mimetype=json_mimeType)
else:
json_data = {"status": ERROR}
return HttpResponse(json.dumps(json_data), mimetype=json_mimeType)
when i print request.FILES, it is empty : . and django raise this MultiValueDictKeyError exeption. what is problem? thanks
I've been trying this for the best part of two weeks now, and I am really stuck. Initially I had created a simple ObjectOutputStream client - server program - with the client being the Android app, but it does not work (it reads the connection but not the object).
So now I am confused as to what other approaches I might be able to take to carry out this simple task? Can anyone Help?
have you tried URLConnection using post method? :)
Or get method like:
String yourURL = "www.yourwebserver.com?value1=one&value2=two";
URL url = new URL(yourURL);
URLConnection connection = url.openConnection();
BufferedReader in = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
response = in.readLine();
you can try JSON stirng to send data. We have a lot of stuff available on how to work with JSON and also there are many api's. JSONSimple is the one I can suggest. Its really easy.
why don't you try this:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
You can use this to post an Entity to server:
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost(url);
postRequest.setEntity(entity);
try {
HttpResponse response = httpClient.execute(postRequest
);
String jsonString = EntityUtils.toString(response
.getEntity());
Log.v(ProgramConstants.TAG, "after uploading file "
+ jsonString);
return jsonString;
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
An Entity can be name value pair:
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("key1", value1));
nvps.add(new BasicNameValuePair("key2", value2));
Entity entity=new UrlEncodedFormEntity(nvps, HTTP.UTF_8)
Or you can send an entity with bytearray.
Bitmap bitmapOrg=getBitmapResource();
ByteArrayOutputStream bao = new ByteArrayOutputStream();
bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 90, bao);
byte[] data = bao.toByteArray();
MultipartEntity entity=new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE)
entity.addPart("file", new ByteArrayBody(data, "image/jpeg",
"file"));
If you want to post json to server:
Please check out this link How do I send JSon as BODY In a POST request to server from an Android application?
For serializing and deserializing java object, I recommend https://sites.google.com/site/gson/gson-user-guide#TOC-Using-Gson
Really hope it can help you see an overview of sending data to server
I have a web service which requires me to send file data to HTTP url with PUT request. I know how to do that but in Android I don't know it.
The API docs gives a sample request.
PUT /images/upload/image_title HTTP/1.1
Host: some.domain.com
Date: Thu, 17 Jul 2008 14:56:34 GMT
X-SE-Client: test-account
X-SE-Accept: xml
X-SE-Auth: 90a6d325e982f764f86a7e248edf6a660d4ee833
bytes data goes here
I have written some code but it gives me error.
HttpClient httpclient = new DefaultHttpClient();
HttpPut request = new HttpPut(Host + "images/upload/" + Name + "/");
request.addHeader("Date", now);
request.addHeader("X-SE-Client", X_SE_Client);
request.addHeader("X-SE-Accept", X_SE_Accept);
request.addHeader("X-SE-Auth", Token);
request.addHeader("X-SE-User", X_SE_User);
// I feel here is something wrong
File f = new File(Path);
MultipartEntity entity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
entity.addPart("photo", new FileBody(f));
request.setEntity(entity);
HttpResponse response = httpclient.execute(request);
HttpEntity resEntityGet = response.getEntity();
String res = EntityUtils.toString(resEntityGet);
Is there something wrong I am doing?
try something similar to
try {
URL url = new URL(Host + "images/upload/" + Name + "/");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("PUT");
// etc.
} catch (Exception e) { //handle the exception !}
EDIT - another and better option:
Using the built-in HttpPut is recommended - examples see http://massapi.com/class/org/apache/http/client/methods/HttpPut.java.html
EDIT 2 - as requested per comment:
Use setEntity method with for example new FileEntity(new File(Path), "binary/octet-stream"); as param before calling execute to add a file to the PUT request.
The following code works fine for me:
URI uri = new URI(url);
HttpClient httpclient = new DefaultHttpClient();
HttpPost post = new HttpPost(uri);
File file = new File(filename);
MultipartEntity entity = new MultipartEntity();
ContentBody body = new FileBody(file, "image/jpeg");
entity.addPart("userfile", body);
post.setEntity(entity);
HttpResponse response = httpclient.execute(post);
HttpEntity resEntity = response.getEntity();
How to transfer a 50mb file to web server using httppost.
When trying to transfer the file it shows out of memory error.
can we use chuncked encoding? how? give some code snippets.
Thank you.
Edit:
Here's the code:
InputStreamEntity reqEntity = new InputStreamEntity(new FileInputStream(f), -1);
reqEntity.setContentType("binary/octect-stream");
reqEntity.setChunked(true);
httppost.setEntity(reqEntity);
Use InputStreamEntity as it does not load the whole file in memory. Do something like this:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://localhost/upload");
File file = new File("/path/to/myfile");
FileInputStream fileInputStream = new FileInputStream(file);
InputStreamEntity reqEntity = new InputStreamEntity(fileInputStream, file.length());
httppost.setEntity(reqEntity);
reqEntity.setContentType("binary/octet-stream");
HttpResponse response = httpclient.execute(httppost);
HttpEntity responseEntity = response.getEntity();
if (responseEntity != null) {
responseEntity.consumeContent();
}
httpclient.getConnectionManager().shutdown();