I have a REST web service and android. Now I want to request Http Put using android to call web service. In my REST web service if user want to do Http Put he can request in terminal like this :
curl -H "Content-Type:application/vnd.org.snia.cdmi.dataobject" -v -T /home/student1/a.jpg http://localhost:8080/user1/folder/a.jpg
My question is how to set -T /home/student1/a.jpg in android using HttpPut?
Here is some snippet you can use:
File f = new File(...);
...
...
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPut httpPut = new HttpPut("http://mydomain.com/some/action");
MultipartEntity entity = new MultipartEntity();
entity.addPart("myFile", new FileBody(f));
httpPut.setEntity(entity);
HttpResponse response = httpclient.execute(httpPut);
Related
I would like the users of my Android app to be able to send zip files to my server using http. The use case I am imagining looks like this:
The user sends a zip file and a String containing a password using a HttpClient and HttpPost (as described here) to my server.
By logging in to www.example.com/my_app with existing password, users can download the files that the people have sent to my server under the given password.
I don't understand how to do the second step. What code do I need to write on my website to receive files that the Android users have been sending? I have a shared server under my hosting plan and a simple website.
You first need to modify the upload code(Since file upload is treated as multipart data).
Here is the modified upload code--
String url = "http://localhost/upload.php";
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath(),
"file.txt");
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
Part[] parts = new Part[1];
parts[0] = new FilePart("fileToUpload", file);
MultipartEntity reqEntity = new MultipartEntity(parts);
reqEntity.setContentType("binary/octet-stream");
reqEntity.setChunked(true); // Send in multiple parts if needed
httppost.setEntity(reqEntity);
HttpResponse response = httpclient.execute(httppost);
} catch (Exception e) {
e.printStackTrace();
}
Here I have used the fileToUpload as the parameter key for uploaded file. On server code you can use the same key for your $_FILES["fileToUpload"].
Here is the simplest PHP code to accept the uploaded data from above android code--
<?php
$target_dir = "/Users/chauhan/Desktop/uploads/";
$target_file = $target_dir . basename("abc.txt");
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file);
?>
I m using the following code to upload file to a server. It works quite well in localhost and bluehost. But it is not working in some hosting like(Go Daddy). Would anybody explain why???
data = IOUtils.toByteArray(inputStream);
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(upload_url);
InputStreamBody inputStreamBody = new InputStreamBody(new ByteArrayInputStream(data), fileName);
CustomMultiPartEntity multipartEntity = new CustomMultiPartEntity();
multipartEntity.setUploadProgressListener(this);
multipartEntity.addPart("pdf", inputStreamBody);
multipartEntity.addPart("title", new StringBody(title));
multipartEntity.addPart("subject", new StringBody(subject));
multipartEntity.addPart("college", new StringBody(college));
multipartEntity.addPart("stream", new StringBody(stream));
multipartEntity.addPart("branch", new StringBody(branch));
multipartEntity.addPart("userID", new StringBody(String.valueOf(userid)));
httpPost.setEntity(multipartEntity);
HttpResponse httpResponse = httpClient.execute(httpPost);
I performed a lot of testing. When I retrieve the values via $_POST[] in the server, the value is null. HttpUrlConnection works in all server. But we have to write everything ourselves. I mean why to write so much code from scratch for a simple function like upload... Is there no library with simple callbacks.?
HttpClient, HttpPost.. are deprecated in API 22, So you should try to use HttpURLConnection instead.
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
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.
I am trying to fetch current user info after making him log into his box, using the box sdk for android. In the box api documentation, they have mentioned everything using curls. I am not familiar with curl. So, can anyone please give me a java equivalent for this curl operation :
curl https://api.box.com/2.0/users/me-H "Authorization: Bearer ACCESS_TOKEN".
I have the users access token.So, please give me a java equivalent for the above curl operation.
You can use java HttpClient
HttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(URL);
httpPost.setHeader("Authorization", "Bearer ACCESS_TOKEN"); // add headers if needded
//set params
BasicNameValuePair[] params = new BasicNameValuePair[] {new BasicNameValuePair("param1","param value"),
new BasicNameValuePair("param2","param value")};
UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity( Arrays.asList(params), "utf-8");
httpPost.setEntity(urlEncodedFormEntity);
//execute request
HttpResponse response = client.execute(httpPost);
HttpEntity entity = response.getEntity();
String body = EntityUtils.toString(entity); //here response in string you can parse it
The HttpClient object that the other answer proposes is now deprecated. I solved a CURL problem like yours (with the extra difficulty of uploading a .wav file). Check out my code in this this answer/question. How to upload a WAV file using URLConnection
Actually I'm using HttpClient() and HttpPost() methods for downloading the html source
here is the code for downloading:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(_url);
try {
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
responseBody = EntityUtils.toString(response.getEntity());
}
If I execute the above code some sites like www.google.com (which will give user agent specific code (HTML code)), not giving whole information suitable for android. So I can tell the host that I'm requesting webpage from android device.