ninjaxelite
ninjaxelite

Reputation: 1178

Android - send data to server with HttpURLConnection

I was following this tutorial to upload images with android: here

After the line conn.setRequestProperty("uploaded_file", fileName); in function uploadFile(String sourceFileUri) I added further lines with conn.setRequestProperty("title", "example"); conn.setRequestProperty("name", "simple_image"); but in the php file I am not receiving these strings with $_POST or $_GET only the image is uploaded.

Is this tutorial here only for uploading images?

I would like to send with the image some other data too. How could I do this?

Thank you

Upvotes: 0

Views: 673

Answers (1)

Sash_KP
Sash_KP

Reputation: 5591

Yes that tutorial is for uploading a single file only.If you want to send some other data(may be some strings) along with your image, then you can use MultipartEntityBuilder.However to use this you need to download the jars from the Apache HttpComponents site and add them to project and path(just add the httpclient jar to your libs folder).

Now for uploading an image along with some string data you can use (may be inside doInBackground of your AsynTask)

File file = new File("yourImagePath");
String urlString = "http://yoursite.com";
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(urlString);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
/* setting a HttpMultipartMode */
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
/* adding an image part */
FileBody bin1 = new FileBody(file);
builder.addPart("uploadedfile1", bin1);
builder.addPart("user", new StringBody("Some String",ContentType.TEXT_PLAIN));//adding a string
HttpEntity reqEntity = builder.build();
post.setEntity(reqEntity);
HttpEntity resultEntity = httpResponse.getEntity();
String result = EntityUtils.toString(resultEntity);

P.S : I assumed you are using AsyncTask for uploading process and that's the reason i said to use this code inside doInBackground of your AsyncTask.

You can use MultipartEntity too.Follow this tutorial which describes how to upload multiple images along with some other string data using MultipartEntity.However there's not much difference in the implementation of MultipartEntity and MultipartEntityBuilder.Try yourself to learn both.Hope these info help you.

Upvotes: 1

Related Questions