I use google-api-client for android. I try to do multipart POST request with text data and image file. Code snippet for creating request is below:
InputStream stream = new FileInputStream(fileToSend);
InputStreamContent photoContent = new InputStreamContent("image/jpeg", stream);
MultipartRelatedContent multiContent =
new MultipartRelatedContent(content, photoContent);
HttpRequest request = getRequestFactory().buildPostRequest(googleUrl, multiContent);
content is key-value text content. As a result I get error 500.
What I'm doing wrong?
There is a guide here about how to do media upload with the google-api-java-client here:
https://code.google.com/p/google-api-java-client/wiki/MediaUpload
That said, I don't anything necessarily wrong with your code either. It is possible that the googleUrl is incorrect, or that content is not properly formatted. You might want to try adding a URL query parameter uploadType=multipart to specify that you are using multipart as the protocol.
Related
For the next step of my application, I need to add download functionality. The user chooses what they want to download and could select anything from 1 file to thousands of them if they could be bothered to select that many.
I want to use Android's built in DownloadManager to provide this downloading functionality, but unfortunately I cannot see how I could implement it for my scenario.
In order for the target server to authorize the download, I need to send some JSON along in the request body. Like this, if I was doing it manually:
DataOutputStream output = new DataOutputStream(connection.getOutputStream());
output.writeBytes(rawData);
output.flush();
Where rawData is the JSON string. The request body is always set to POST.
I can't seem to find any way to add this JSON string to the DownloadManager, and until I can do that, the server will always reject the download.
The only other solution that I can think of, which I desperately want to avoid, is writing a PHP script on my server to take some GET parameters, generate the JSON and then redirect the request.
Does anybody know of a way that I can send my JSON data along with the DownloadManager? Each file that I'm downloading needs its own, unique, JSON string.
you cannot do that in Android's Download manager, see Download Manager Issue,
I had a similar requirement and I ended up Using HttpClient (Xamarin).
Sample Code-
using(var httpClient = new HttpClient()) {
using(var request = new HttpRequestMessage(new HttpMethod("POST"), URL)) {
request.Headers.TryAddWithoutValidation("User-Agent", userAgent);
request.Headers.TryAddWithoutValidation("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
request.Headers.TryAddWithoutValidation("Accept-Language", "en-US,en;q=0.5");
request.Headers.TryAddWithoutValidation("Connection", "keep-alive");
request.Headers.TryAddWithoutValidation("Referer",RefererURL);
request.Content = new StringContent("YOUR_REQUEST_BODY_HERE");
request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/x-www-form-urlencoded");
var responser = await httpClient.SendAsync(request);
return responser;
}
I am new in android . i have send image to server using Json format as a string.
so i have Encoded image string i.e base64 string.
Json j = new JSonObject();
String Image_string = Base64.ToEncodedString(bytearray, Base64.Default);
j.put("image_file_content",Image_string);
But i am getting this error.
Please help me..wts wrong
400 Bad Request
Bad Request
Your browser sent a request that this server could not understand.
Additionally, a 404 Not Found
error was encountered while trying to use an ErrorDocument to handle the request.
Consider using URLEncoder
URLEncoder.encode("String to encode", "UTF-8");
Check out the docs here: http://developer.android.com/reference/java/net/URLEncoder.html
I am posting a string to server. If string size is up to 6000KB then its posted successfully. But when size exceeded more than this its showing response -1.
I have tried method of posting: syn_data1 is string . records fetch from data base and then appending to A string builder and finally i create synData1 string from String builder
URL url = new URL(syn_data1);
URLConnection urlc = url.openConnection();
HttpURLConnection huc = (HttpURLConnection)urlc;
huc.setRequestMethod("POST");
huc.setConnectTimeout(3000);
huc.connect();
int response = huc.getResponseCode();
I do care about each special character and remove.But I did not get success
In theory, the URI in an HTTP request can be of any length, but the practical limit is on the order of 2k. Please read here for more info on that.
I am assuming the length is coming from the query string parameters (those name=value pairs that come after the ?). You should be putting these in the POST data, leaving the path part of the URI only. Of course, the server will have to be looking for those parameters in the POST data as well.
Are you passing the NameValue pairs properly . This is one successful way which i use .
List<NameValuePair> loginParams = new ArrayList<NameValuePair>(1);
loginParams.add(new BasicNameValuePair("ColumnName In DB",YourString));
then you do
httppost.setEntity(new UrlEncodedFormEntity(loginParams));
and proceed to execute
It's not clear exactly what you're trying to achieve, but this definitely looks wrong:
URL url = new URL(syn_data1.toString());
URLEncoder.encode(syn_data1.toString(),"UTF-16BE");
If syn_data1 is already a string, you don't need to call toString on it.. and calling URLEncoder.encode doesn't have any side-effects, so the second statement is pointless. Perhaps you want:
URL url = new URL(URLEncoder.encode(syn_data1, "UTF-16BE"));
That's just on the encoding side though - you still shouldn't be trying to use enormous URLs. If you have a lot of data, that should be in the body of the request rather than the URL.
On Android phone, I used setEntity() to put the FileEntity to the POST request.
HttpPost post = new HttpPost(uri);
FileEntity reqEntity = new FileEntity(f, "application/x-gzip");
reqEntity.setContentType("binary/octet-stream");
reqEntity.setChunked(true);
post.addHeader("X-AethersNotebook-Custom", configuration.getCustomHeader());
post.setEntity(reqEntity);
When using bottle, tried this but it is not working
f = request.body
gzipper = gzip.GzipFile( fileobj= f )
content = gzipper.read()
The content will be an empty string. So I tried to look at request.forms and request.files. Both of them have no key and value.
request.files.keys()
request.forms.keys()
When searching, I read about the entity: "a request MAY transfer entity" and the entity has entity-header and entity-value. So it may be something like file-content = e.get(entity-header).
Using that code, the phone send file using chunked encoding. Because py-bottle does not support chunked enconding, the solution here is rewrite the android to send file as body of POST request.
i'm creating an activity which needs to upload an image to a webservice using their api.
I found that if i use UrlEncodedFormEntity and send the image data through that. the webservice doesn't receive that. ( at least it will not be able to read that .)
In fact if i add some vars to send with the image data ( like name of the file, filesize ) they can be read from the webservice but the image data still doesn't appear if i try to read it serverside.
Right now i'm using UrlEncodedFormEntity with BasicNameValuePair as container for my data.
May be it will help you.
I've used the same functionality, but the web service was developed by me. I've post the image using the following:
I get the particular Bitmap icon and compress it in byte array like this:
ByteArrayOutputStream out = new ByteArrayOutputStream(10240);
icon.compress(CompressFormat.PNG, 100, out);
Then create HttpPost and set the the entity.
httpPostInstance.setEntity(new ByteArrayEntity(out.toByteArray()));
Check the "Content-type" header. You must properly set it to whatever your service expect.