I am trying to write a program in android that uploads a file to server. I want to use apache httpclient for that.
Here is my code:
String url = "http://192.168.1.103:8080";
File file = new File("/sdcard/alireza/ali.txt");
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);
Toast.makeText(getApplicationContext(),"executing...",Toast.LENGTH_LONG).show();
HttpResponse response = httpclient.execute(httppost);
Toast.makeText(getApplicationContext(),"done",Toast.LENGTH_LONG).show();
//Do something with response...
}catch (Exception e){
}
The done toast doesn't appear.
Related
I am uploading a File from GWT to a different domain
File Uploads well , But the response i sent from the server always reaches as "null" at the client side
response.setContentType("text/html");
response.setHeader("Access-Control-Allow-Origin", "*");
response.getWriter().print("TEST");
response is NULL only when i upload the file on a different domain ... (on same domain all is OK)
I also see this in GWT documentation
Tip:
The result html can be null as a result of submitting a form to a different domain.
http://www.gwtproject.org/javadoc/latest/com/google/gwt/user/client/ui/FormPanel.SubmitCompleteEvent.html
Is there any way I can receive back a response at my client side when i am uploading file to a different domain
There are 2 possible answer:
Use JSONP Builder
JsonpRequestBuilder requestBuilder = new JsonpRequestBuilder();
requestBuilder.requestObject(url, new AsyncCallback<FbUser>() {
#Override
public void onFailure(Throwable ex) {
throw SOMETHING_EXCEPTION(ex);
}
#Override
public void onSuccess(ResponseModel resp) {
if (resp.isError()) {
// on response error on something
log.error(resp.getError().getMessage())
log.error(resp.getError().getCode())
}
log.info(resp.getAnyData())
}
Not to use GWT to upload, rather use other client like apache HttpClient
public uploadFile() {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(url);
FileBody bin = new FileBody(new File(UPLOADED_FILE));
long size = bin.getContentLength();
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("PART", bin);
String content = "-";
try {
httpPost.setEntity(reqEntity);
HttpResponse response = httpClient.execute(httpPost, localContext);
HttpEntity ent = response.getEntity();
InputStream st = ent.getContent();
StringWriter writer = new StringWriter();
IOUtils.copy(st, writer);
content = writer.toString();
} catch (IOException e) {
return "false";
}
return content;
}
Hope it helps
I am using HttpClient to send a request with JSON and MP3 audio content. Can anybody tell me where the below code goes wrong? I am using HttpClient version 4.5.2.
HttpClient httpClient = HttpClientBuilder.create().setUserAgent("MyAgent").setMaxConnPerRoute(4).build();
HttpPost httpPostRequest = new HttpPost("url");
httpPostRequest.addHeader("content-type","multipart/form-data");
File audioFile = new File("filename.mp3");
FileBody fileBody = new FileBody(audioFile);
StringBody jsonStringBody = new StringBody(gson.toJson(pojoObject).toString(), ContentType.MULTIPART_FORM_DATA);
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
multipartEntityBuilder.setContentType(ContentType.MULTIPART_FORM_DATA);
multipartEntityBuilder.addPart("file", fileBody);
multipartEntityBuilder.addPart("jsonMetaData", jsonStringBody);
HttpEntity entity = multipartEntityBuilder.build();
httpPostRequest.setEntity(entity);
HttpResponse response = httpClient.execute(httpPostRequest);
I use httpclient to post img to website.
But I have tucked it into httpclient.execute(httppost).
In my local environment , I run it perfect. But when i publish project to SinaAppEngine(Java Local IO
restricted)->sae ,execute method doesn't work because code like this:
reqEntity.addPart("image", byteArrayBody);
(Stringbody run normally )
My sample code:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://r.catchoom.com/v1/search");
ByteArrayBody byteArrayBody = new ByteArrayBody(imgByte, "test.jpg");
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("image", byteArrayBody);
httppost.setEntity(reqEntity);
HttpResponse response = httpclient.execute(httppost);
On PHP Side I am using following Code
$val = (isset($_GET['file']) ? $_GET['file'] : null);
$isUploaded = false;
return $val;
if($val != null)
{
if (move_uploaded_file(#$_FILES['file']['tmp_name'], $mainPath))
{
$isUploaded = true;
}
}
Android side I am using
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("file", Base64Coder.encodeLines(imageArray)));
HttpResponse response = null;
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter("http.connection-manager.timeout", 15000);
try {
HttpPost httppost = new HttpPost(url);
httppost.setEntity(entity);
response = httpclient.execute(httppost);
However
$val = (isset($_GET['file']) ? $_GET['file'] : null);
returns null
How can I upload image properly
This is my code for upload, and it's work. You need import httpmime jar
PHP code
$uploads_dir = '/Library/WebServer/Documents/Upload/upload/'.$_FILES['userfile']['name'];
if(is_uploaded_file($_FILES['userfile']['tmp_name'])) {
echo $_POST["contentString"]."\n";
echo "File path = ".$uploads_dir;
move_uploaded_file ($_FILES['userfile'] ['tmp_name'], $uploads_dir);
} else {
echo "\n Upload Error";
echo "filename '". $_FILES['userfile']['tmp_name'] . "'.";
print_r($_FILES);
JAVA code
HttpClient client = new DefaultHttpClient();
HttpPost postMethod = new HttpPost("http://localhost/Upload/index.php");
File file = new File(filePath);
MultipartEntity entity = new MultipartEntity();
FileBody contentFile = new FileBody(file);
entity.addPart("userfile",contentFile);
StringBody contentString = new StringBody("This is contentString");
entity.addPart("contentString",contentString);
postMethod.setEntity(entity);
HttpResponse response = client.execute(postMethod);
HttpEntity httpEntity = response.getEntity();
String state = EntityUtils.toString(httpEntity);
$val = (isset($_GET['file']) ? $_GET['file'] : null);
Replace with
$val = (isset($_FILES['file']['name']) ? $_FILES['file']['name'] : null);
Check manual for available fields for post method uploads.
http://www.php.net/manual/en/features.file-upload.post-method.php
I'am trying to convert many doc files via an online website, using HttpClient to emulate an Http request
URI uri = new URI("http://www.docx2doc.com/convert/convert-file");
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(uri);
MultipartEntity reqEntity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("email",new StringBody(""));
reqEntity.addPart("input_type",new StringBody("doc"));
reqEntity.addPart("output_type",new StringBody("html"));
reqEntity.addPart("script",new StringBody("converters"));
FileBody bin = new FileBody(
new File("mydoc.docx"));
reqEntity.addPart("input_file", bin );
httppost.setEntity(reqEntity);`
all the parameters (email,output_type...) in the post are accepted by the server but not the file ...
how can I handle this ?
Thank You.