logo
Tags down

shadow

Upload arraylist using httpurlconnection multipart/form-data


By : Satya
Date : September 16 2020, 06:00 PM
will help you NOTE that I have not tried if this code acctually works with the HttpURLConnection but it should.
From what I've read from the internet you can still use that loop you mentioned but with some modifications.
code :
--boundary
Content-Disposition: form-data; name="something1"

data1
--boundary
Content-Disposition: form-data; name="something2"

data2
--boundary--
public byte[] get_multipart_data(List<String> files, String boundary)
loop for all files
    write "--boundary"
    write "Content-Disposition: ...."
    write image_data
end
write "--boundary--"
ByteArrayOutputStream message = null;
DataOutputStream stream = null;

FileInputStream fileInputStream;

int maxBufferSize = 1024 * 1024;
byte[] buffer = new byte[maxBufferSize];
byte[] sendData = new byte[0];
try {
    message = new ByteArrayOutputStream();
    stream = new DataOutputStream(message);

    // Loop though all file names
    for(String fileName : files) {
        stream.writeBytes("--" + boundary + "\r\n"); // Start boundary
        stream.writeBytes("Content-Disposition: form-data; name=\"" + fileName + "\"\r\n\r\n");

        // Read the image data
        fileInputStream = new FileInputStream(fileName);
        int readBytes = 0;
        while((readBytes = fileInputStream.read(buffer)) != -1) {
            // Write file data to output
            stream.write(buffer, 0, readBytes);
        }
        fileInputStream.close();

        stream.writeBytes("\r\n");
    }
    stream.writeBytes("--" + boundary + "--\r\n"); // Closing boundary

    sendData = message.toByteArray();
} catch(IOException e) {
    e.printStackTrace();
}


Share : facebook icon twitter icon

Passing parameters along with a multipart/form-data upload form (Java Http Post Upload)


By : user3247331
Date : March 29 2020, 07:55 AM
hop of those help? If isFormField on FileItemStream returns true it's a normal field. You can use openStream and read the contents into a String.
Something like this:
code :
FileItemStream item = iter.next();
if(item.isFormField()) {
   // Normal field
   String name = item.getFieldName();
   String value = Streams.asString(item.openStream());
} else {
   // File
}

HttpUrlConnection multipart-form-data return error 422 Unprocessable Entity


By : jassi
Date : March 29 2020, 07:55 AM
To fix this issue Finally I have built it successfully. here it's the solution
Add the following to the gradle
code :
android {
    compileSdkVersion 23
    buildToolsVersion "23.0.2"
    useLibrary  'org.apache.http.legacy'
    ...
    dependencies {
             compile 'org.apache.httpcomponents:httpmime:4.3.1'
             compile group: 'org.apache.httpcomponents' , name: 'httpclient-android' , version: '4.3.5.1'
public void executeMultipartPost(Bitmap bm) throws Exception {
        try {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            bm.compress(Bitmap.CompressFormat.PNG, 75, bos);
            byte[] data = bos.toByteArray();
            HttpClient httpClient = new DefaultHttpClient();
            HttpPost postRequest = new HttpPost(url);
            ByteArrayBody bab = new ByteArrayBody(data, getString(R.string.file_path));

            MultipartEntity reqEntity = new MultipartEntity(
                    HttpMultipartMode.BROWSER_COMPATIBLE);

            postRequest.addHeader("access_token", auth);

            reqEntity.addPart("type", new StringBody("image"));
            reqEntity.addPart("postId", new StringBody(postId));
            reqEntity.addPart("file", bab);


            postRequest.setEntity(reqEntity);
            HttpResponse response = httpClient.execute(postRequest);
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    response.getEntity().getContent(), "UTF-8"));
            String sResponse;
            StringBuilder s = new StringBuilder();

            while ((sResponse = reader.readLine()) != null) {
                s = s.append(sResponse);
            }
            System.out.println("Response: " + s);
        } catch (Exception e) {
            // handle exception here
            Log.e(e.getClass().getName(), e.getMessage());
        }
    }

HTTPURLConnection - POST multipart/form-data with large file with FixedLengthStreamingMode


By : Carlos Delgado
Date : March 29 2020, 07:55 AM
wish helps you So I'm trying to send a multipart/form-data POST request with large image file. I can't pre-convert file to byte array, my app will crash with OutOfMemory exception, so I have to write contents of the file directly to connection's outputstream. Also, my server doesn't support chunked mode, so I have to calculate content length before sending data and use connection's setFixedLengthStreamingMode. , conn.disconnect() after outputStream.close()

Android to PHP: epipe Broken Pipe / stream closed posting chunked multipart form-data using httpurlconnection


By : Sandeep S
Date : March 29 2020, 07:55 AM
I wish this help you As stated here you should call either setFixedLengthStreamingMode(len) when the body length is known in advance, or setChunkedStreamingMode(0) when it is not. About the broken pipe error, note that, if possible, android will reuse the old socket connection since establishing a connection is a resource consuming operation in a mobile environment. Try to force the POST to be performed over a new connection:

simple HttpURLConnection POST file multipart/form-data from android to google blobstore


By : Brumaire
Date : March 29 2020, 07:55 AM
wish helps you I am using HttpURLConnection to achieve this.
Create one Multipart custom class ::
Related Posts Related Posts :
  • Unable to resolve datatable after migrated from Cucumber 1 to Cucumber 4
  • Absolute file paths when running program from jar?
  • How do I let the elements in my Array move by +1, whenever a new element joins
  • Read HDF5 in streaming in java
  • How to rollback the first transaction and not rollback the new transaction?
  • "debuggable false" is enough to prevent debugging my App?
  • Vert.x JWT auth gives Forbidden access
  • Null object reference on navigationview based fragment recycler view
  • Java 8 lambda mutable variable capture from method parameter?
  • Unable to click on the link though not inside any frame or iframe or window
  • What's the purpose of ThreadLocal here?
  • Toast method for displaying messages
  • How many bytes of English and Chinese characters take in java?
  • Trying to iterate through a String and find if char is a letter or digit then append it to a different String
  • @valid annotation is not working as expected
  • Failed to run the DB2 command using jdbc
  • @ManyToOne and @OneToOne on the same entity
  • Should I explicitly implement an interface when I already extend a class that implements it?
  • AndroidStudio - TextInput hide characters when keyboard shows up
  • How to avoid flow stopping in case of handler returns null?
  • Rename all JSON keys - Java - Jackson - springboot
  • Not able to convert char[] as list in java
  • Firebase Cloud Notification causing Application to crash
  • Thrown java.sql.SQLSyntaxErrorException: ORA-00911: invalid character and unable to find the reason in Netbeans
  • How can I convert String() into Int() in Processing?
  • How to test a function in an abstract class that implements another class
  • Loop Validation
  • NoSuchFileException using File.copy
  • How to instantiate Remote Web Driver so I can run tests in parallel using Java and Selenium with Serenity
  • Only handling tree will expand but not tree selection in JTree - Java Swing
  • Cannot call a method with a type after an instanceof check
  • Trying to give the object correct parameters
  • Comparator<? super T> as functions parameter- how use?
  • how can i launch my app or an activity on notification received when app is in background or killed?
  • checking the input for primitive data types in java
  • How to match original password with encrypted password entry in database on login
  • How to clear ComboBoxes that are in an HBox when clicking a button?
  • Is there an IList in java and how to use it and when?
  • I don't think that my array is storing and data
  • Why does LocalDateTime fails to parse from string?
  • Is it advisable to have a static block inside static inner class
  • is parameter of main method eligible for garbage collection?
  • I want to create a straight line connecting 2 JTable together
  • Java's toString() static or non-static (based on my example)
  • Last date of next month in Java
  • Androidx migration: NoClassDefFoundError
  • Deep JSON structures to Java object, is there a better way than what I did? It looks horrendous
  • Make ssl-context-support conditional with tcp-connection-factory using Spring Integration
  • Check if an item is a specific ArrayList instead of one with equal values
  • Android Studio emulator keeps stopping
  • How to change the first row and column in a 2D array
  • How to extend a class having parameterized @BeforeMethod
  • Which one is the fastest beween Set and Maps in Java?
  • How to .save/POST an array of values from a JSON key value pair in Java spring-boot JPA
  • AES encrypt any java object to a base64 string
  • XPath to select preceding input
  • Java: KeyListeners does work, but only works when I type space
  • How can I get columns for a specific table using jOOQ without pulling all table metadata into memory?
  • IllegalStateException : a relationship that was not marked cascade PERSIST
  • How to get the value without round up/down in Java?
  • shadow
    Privacy Policy - Terms - Contact Us © 35dp-dentalpractice.co.uk