i know for uploading audio in android, i can do like this :
final byte[] data = out.toByteArray();
String urlString = "http://localhost/voiceupload.php";
HttpPost postRequest = new HttpPost(urlString);
postRequest.setEntity(new ByteArrayEntity(data)); //data is a byte array containing sound in the form of bytearray
HttpClient client = new DefaultHttpClient();
for uploading simple values i can do like this :
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("callid", "8123069127952"));
UrlEncodedFormEntity formEntity = null;
try {
formEntity = new UrlEncodedFormEntity(postParameters);
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
httpPost.setEntity(formEntity);
client.execute(postRequest)
Now i want to send both in one post request.I mean i want to send one or more variable values and one sound file.Can i do this ?
Sure. See my answer at this post:
Save a received picture to a folder on a web server
Just replace the image file with the sound file.
Where it passes just one value, the filename, you can add as many name-value pairs as you'd like.
Related
i want to upload a file to server php using post
Heres my code
String url = "http://blabla.com/upload.php";
File file = new File(Environment.getExternalStorageDirectory(),
"Myfile.log");
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
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...
}
My question is how can i handle it on php ? If its in $_FILES array then what id i should use to put it in uploads folder ($_FILES['whatShouldBeHere'] )? Thanks .
Hi I'm trying to send an ArrayList as a parameter for a POST request from my Android app to a server. So far I have this code:
HttpResponse response;
List<NameValuePair> postParams = new ArrayList<NameValuePair>(2);
postParams.add(new BasicNameValuePair("post[text]", text));
postParams.add(new BasicNameValuePair("post[common_comments]", String.valueOf(commonComments));
postParams.add(new BasicNameValuePair("post[wall_ids]", wallIds);
UrlEncodedFormEntity encodedParams;
try {
encodedParams = new UrlEncodedFormEntity(postParams);
post.setEntity(encodedParams);
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
but BasicNameValuePair only receives String as value. Is there any way I can send an ArrayList as a value for post[wall_ids]?
Thanks in advance.
Bueno días Carla.
I don´t know if you had resolve this (two months is a lot of time)... but maybe it can help you:
for(String wallyID: wallyIDs)
postParams.add(new BasicNameValuePair("extraFields[wallyIDs][]", wallyID));
It would also be good to use the "utf 8" format, if you want to use latin characters (this will make to forget on the server), something like:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
httppost.setEntity(new UrlEncodedFormEntity(postParams, HTTP.UTF_8));
I have a question about the List constructor... why do you use 2 as argument for it??
PS: I would like to make a coment and not an answer, because I don´t know if it could work as you want.
I intend to send a simple http post request with a large string in the Payload.
So far I have the following.
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("address location");
String cred = "un:pw";
byte[] authEncBytes = Base64.encodeBase64(cred.getBytes());
String authStringEnc = new String(authEncBytes);
httppost.setHeader("Authorization","Basic " + authStringEnc);
However, I do not know how to attach a simple RAW string into the payload. The only examples I can find are name value pairs into the Entity but this is not what I want.
Any assistance?
It depends on the concrete HTTP-API you're using:
Commons HttpClient (old - end of life)
Since HttpClient 3.0 you can specify a RequestEntity for your PostMethod:
httpPost.setRequestEntity(new StringRequestEntity(stringData));
Implementations of RequestEntity for binary data are ByteArrayRequestEntity for byte[], FileRequestEntity which reads the data from a file (since 3.1) and InputStreamRequestEntity, which can read from any input stream.
Before 3.0 you can directly set a String or an InputStream, e.g. a ByteArrayInputStream, as request body:
httpPost.setRequestBody(stringData);
or
httpPost.setRequestBody(new ByteArrayInputStream(byteArray));
This methods are deprecated now.
HTTP components (new)
If you use the newer HTTP components API, the method, class and interface names changed a little bit, but the concept is the same:
httpPost.setEntity(new StringEntity(stringData));
Other Entity implementations: ByteArrayEntity, InputStreamEntity, FileEntity, ...
i was making a common mistake sequence of json object was wrong. for example i was sending it like first_name,email..etc..where as correct sequence was email,first_name
my code
boolean result = false;
HttpClient hc = new DefaultHttpClient();
String message;
HttpPost p = new HttpPost(url);
JSONObject object = new JSONObject();
try {
object.put("updates", updates);
object.put("mobile", mobile);
object.put("last_name", lastname);
object.put("first_name", firstname);
object.put("email", email);
} catch (Exception ex) {
}
try {
message = object.toString();
p.setEntity(new StringEntity(message, "UTF8"));
p.setHeader("Content-type", "application/json");
HttpResponse resp = hc.execute(p);
if (resp != null) {
if (resp.getStatusLine().getStatusCode() == 204)
result = true;
}
Log.d("Status line", "" + resp.getStatusLine().getStatusCode());
} catch (Exception e) {
e.printStackTrace();
}
return result;
Answer
I am trying to send data to a web server using a post, this is what I have so far:
private void entity(String id, String file)
throws JSONException, UnsupportedEncodingException, FileNotFoundException {
// Add your data
File myFile = new File(
Environment.getExternalStorageDirectory(), file);
InputStreamEntity reqEntity = new InputStreamEntity(
new FileInputStream(myFile), myFile.length());
reqEntity.setContentType("text/csv");
reqEntity.setChunked(true); // Send in multiple parts if needed
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("project", id));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httppost.setEntity(reqEntity);
//httppost.setHeader("Content-Length", String.valueOf(myFile.length()));
}
When I send the post request it comes back with content-length required, but isn't that set here?
InputStreamEntity reqEntity = new InputStreamEntity(
new FileInputStream(myFile), myFile.length());
I don't know if what I am doing is right or not, please help, thanks
Edit -
When I try to set the content-length myself using
httppost.setHeader("Content-Length", String.valueOf(myFile.length()));
it comes back with header already set.
Hence why it is commented out
In my case using
reqEntity.setChunked(false);
solved the problem.
You may want to use MultipartEntity and add parts using addPart methods with StringBody and InputStreamBody (or) FileBody
That sets the length of the content for the InputStreamEntity which is used locally when writing the data to the OutputStream. It doesn't set that value as a parameter for your request. You'll need to set that header yourself.
I need to send post request with data in format like key=value and I am working that like ( url is url of ws and that is ok )
HttpEntityEnclosingRequestBase post=new HttpPost();
String result = "";
HttpClient httpclient = new DefaultHttpClient();
post.setURI(URI.create(url));
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
for (Entry<String, String> arg : args.entrySet()) {
nameValuePairs.add(new BasicNameValuePair(arg.getKey(), arg
.getValue()));
}
http.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response;
response = httpclient.execute(post);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
result = getStringFromStream(instream);
instream.close();
}
return result;
This is ok when I send String data. My question is what to modify when one parameter is picture adn others are strings ?
When you are using multiple data types to send over a HttpClient you must use MultipartEntityBuilder(Class in org.apache.http.entity.mime)
try this out
MultipartEntityBuilder s= MultipartEntityBuilder.create();
File file = new File("sample.jpeg");
String message = "This is a multipart post";
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
System.out.println(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addBinaryBody("upfile", file, ContentType.DEFAULT_BINARY, "sample.jpeg");
builder.addTextBody("text", message, ContentType.DEFAULT_BINARY);
HttpEntity entity = builder.build();
httppost.setEntity(entity);
}
If you are looking to send the image as the data portion of the post request, you can follow some of the links posted in the comments.
If the image / binary data must absolutely be a header (which I wouldn't recommend), then you should use the encodeToString method inside of the Base64 Android class. I wouldn't recommend this for big images though since you need to load the entire image into memory as a byte array before you can even convert it to a string. Once you convert it to a string, its also 4/3 its previous size.
I think the answer you're looking for is in this post:
How to send an image through HTTPPost?
Emmanuel