I'm trying to transfer big file to the server using httpput.
However, I can't to transfer big files. I get IOException with error message: "I/O error during system call, Connection reset by peer".
I'm using the code:
// create authenticate client
DefaultHttpClient client = new DefaultHttpClient(httpParameters);
// create HTTP put with the file
HttpPut httpPut = new HttpPut(url);
final File recordingFile = new File(mDir, mName);
FileEntity entity = new FileEntity(recordingFile, "binary/octet-stream");
entity.setChunked(true);
httpPut.setEntity(entity);
httpPut.addHeader("Connection", "Keep-Alive");
httpPut.addHeader("Content-Type", "application/zip");
// Execute
HttpResponse res = client.execute(httpPut);
int statusCode = res.getStatusLine().getStatusCode();
When sending file through http remember that your server http has a max-limit to dimension of the file.
If i'm not wrong the default value is 2MB: but you can change this on the configuration file of the server (PHP).
The file to check is php.ini.
Open the file and search for 'upload_max_filesize = 2M': simply change 2 with the dimension you need for your project and save.
That's all!
I think you need to change the maximum Request size in the web.config file.
<httpRuntime executionTimeout="110" maxRequestLength="8192" />
Related
I can't manage to upload a JAR file, using Webdav and Apache HTTPClient without leading to "invalid or corrupt jarfile" when I attempt to launch it.
Here's my Setup:
Webdav server, using tomcat 8.5 on an external directory (defined in $CATALINA_HOME/conf/Catalina/localhost/webdav.xml)
Apache HTTP Client (org.apache.httpcomponents:httpclient:4.5.5)
Custom Maven Plugin using HTTP Client to upload the file
File is uploaded using a custom maven plugin (which uses HTTP Client internally) after building the JAR.
If I try to use HTTP Client to upload the file to the remote server, it leads to corruption. But I can launch the Jar without any problemif I send the exact same file using curl command
curl -u <user>:<pass> -T <myjar>.jar http://<remotehost>/<myjar>.jar
Here is the sample code using HTTP Client:
class FileSender {
public static void main(String[] args) {
// [...]
RequestConfig.Builder cfg = RequestConfig.copy(RequestConfig.DEFAULT);
cfg = cfg.setConnectTimeout(timeout)
.setConnectionRequestTimeout(timeout)
.setSocketTimeout(timeout);
CredentialsProvider credentialsProvider = authentication.credentials();
HttpClientBuilder builder = HttpClientBuilder.create()
.setDefaultRequestConfig(cfg.build())
.setDefaultCredentialsProvider(credentialsProvider);
try(CloseableHttpClient client = builder.build()) {
HttpPut httpPut = new HttpPut("http://<remote>/<myJar>.jar");
httpPut.setEntity(MultipartEntityBuilder.create()
.addBinaryBody("file", new File("path/to/<myJar>.jar"))
.build());
try (CloseableHttpResponse response = client.execute(httpPut)) {
// Check response HTTP status
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
Do you have any what might cause my issue ?
Edit: MD5 hashes seems different if I use HTTP Client and CURL, but CURL & FTP copy share the same hashes.
This is the way how you can upload any file with HttpClient:
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpEntity requestEntity = MultipartEntityBuilder.create().addBinaryBody("file", new File("myfile")).build();
HttpPost post = new HttpPost("http://...");
post.setEntity(requestEntity);
try (CloseableHttpResponse response = httpClient.execute(post)) {
System.out.print(response.getStatusLine());
}
Usually POST method is used to upload form or file content.
I solved it by changing this
MultipartEntityBuilder.create()
.addBinaryBody("file", new File("path/to/<myJar>.jar"))
.build()
by this
new InputStreamEntity(new FileInputStream(new File("path/to/<myJar>.jar)))
I'm writing a simple, no UI (hence no .jsp/.html files), console based Java application to read image file paths from a file and upload the images to my sample photo feed application on Google App Engine.
I'm using Apache HttpClient to make the URL connection and the POST request to my app engine application and this is the code I have so far.
MultipartEntity multiPartEntity = new MultipartEntity();
multiPartEntity.addPart("photo", new FileBody(new File(filePath)));
multiPartEntity.addPart("title", new StringBody(comment));
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(uploadUrl);
post.setEntity(multiPartEntity);
HttpResponse response = client.execute(post);
This uploads the file and I can see it in the Blob Viewer. However, the Content-Type of the file is set to "application/octet-stream".
I want the Content-Type to be set to "image/jpeg" or "image/png" or so on depending on the image type. I tried modifying the code a bit using
MultipartEntity multiPartEntity = new MultipartEntity();
multiPartEntity.addPart("photo", new FileBody(new File(filePath), "image/jpeg"));
multiPartEntity.addPart("title", new StringBody(comment));
but this failed to even upload the file into the Blob Viewer and I still get the same response from the application servlet.
Can somebody help me crack this?
i am creating a desktop application which send file to an tomcat server. the servlet receiver and saves file fine.
I need some help to do a java program that post in a https site. I dont know how to put the parameters because it a multpart form data contect type.. Please help! when I do a post with firefox its like this...
This will depend. I've used the following technique to upload a multi-part file to a server before, based on providing a series of form key/name pairs.
This will be depended on you own requirements and what the servlet is actually expecting...
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
String name = file.getName();
entity.addPart(new FormBodyPart("someFormParameter", new StringBody("someFormName")));
/*...*/
entity.addPart("formFileNameParameter", new FileBody(file, mimeType));
HttpClient client = /*...*/
HttpPost post = new HttpPost(url.toURI());
post.setEntity(entity);
HttpResponse response = client.execute(post);
// Process response
I am facing some weird issue with my code. I am using org.apache.http.entity.mime.MultipartEntity class to submit file entity to server so that I can upload the file. But when I am trying to add another entity/parameter, its value is not been able to capture through HttpServletRequest. Below is my client side working code from where I am sending the successful file upload request:
public class TestClass
{
public static void main(String args[]) throws ConfigurationException, ParseException, ClientProtocolException, IOException
{
HttpClient client = new DefaultHttpClient();
client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpPost post = new HttpPost("http://localhost:9090/HostImages/ImageUploaderServlet");
MultipartEntity entity = new MultipartEntity( HttpMultipartMode.BROWSER_COMPATIBLE );
entity.addPart( "file", new FileBody(new File("D:/tempImage/cat_image.jpg") ));
post.setEntity(entity);
String response = EntityUtils.toString( client.execute( post ).getEntity(), "UTF-8" );
client.getConnectionManager().shutdown();
}
}
On the server side, i.e. inside ImageUploaderServlet I was parsing the request object of HttpServletRequest as follows:
FileItemFactory fileItemFactory = new DiskFileItemFactory();
ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory);
List fileItems = servletFileUpload.parseRequest(request);
and it gives me list of file submitted through client side which absolutely work fine.
Problem arises when I am trying to add another entity either by using MultipartEntity or by HttpParams I am unable to get its value at server end. I have gone through this question already posted but no help. (I tried to add another entity as StringBody as below:)
entity.addPart("flag", new StringBody("true"));
I want to add some additional parameters at client side so that I can use that at server side to serve my purpose. Additional parameter could be either String, int or byte whatsoever. I dont know where is the exact problem lies, client side or server side ! Kindly help.
Multipart Requests need special attention. Here is a useful link to a thread that can help to understand how to treat these cases:
Convenient way to parse incoming multipart/form-data parameters in a Servlet
Regards
Right now I am using Httppost to Post some parameters in the form of xml to a server. When the post occurs, a geotiff or .tif file is downloaded. I have successfully posted the document to the server and successfully downloaded the file simply by attaching the parameters to the url but I can't seem to combine the two. I have to use post because just using the URL leaves out elevation data in the geotiff.
In short, I am not sure how to simultaneously post and retrieve the image of the post. This is what I have thus far...
// Get target URL
String strURL = POST;
// Get file to be posted
String strXMLFilename = XML_PATH;
File input = new File(strXMLFilename);
// Prepare HTTP post
HttpPost post = new HttpPost(strURL);
post.setEntity(new InputStreamEntity(
new FileInputStream(input), input.length()));
// Specify content type and encoding
post.setHeader(
"Content-type", "text/xml");
// Get HTTP client
HttpClient httpclient = new DefaultHttpClient();
//Locate file to store data in
FileEntity entity = new FileEntity(newTiffFile, ContentType.create("image/geotiff"));
post.setEntity(entity);
// Execute request
try {
System.out.println("Connecting to Metoc site...\n");
HttpResponse result = httpclient.execute(post);
I was under the impression that the entity would contain the resulting image. Any help is much appreciated!
Thanks for the help guys. The entity was what was being sent to the server. I had code that was trying to read it from the response as well but it wasn't working because setting the entity to a file entity messed up the post request. By removing that part, it works great!