Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 998245
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 16, 20262026-05-16T07:09:49+00:00 2026-05-16T07:09:49+00:00

Hey, I’ve tried researching how to POST data from java, and nothing seems to

  • 0

Hey, I’ve tried researching how to POST data from java, and nothing seems to do what I want to do. Basically, theres a form for uploading an image to a server, and what I want to do is post an image to the same server – but from java. It also needs to have the right parameter name (whatever the form input’s name is). I would also want to return the response from this method.

It baffles me as to why this is so difficult to find, since this seems like something so basic.

EDIT —- Added code

Based on some of the stuff BalusC showed me, I created the following method. It still doesn’t work, but its the most successful thing I’ve gotten yet (seems to post something to the other server, and returns some kind of response – I’m not sure I got the response correctly though):

EDIT2 —- added to code based on BalusC’s feedback

EDIT3 —- posting code that pretty much works, but seems to have an issue:

 ....

 FileItemFactory factory = new DiskFileItemFactory();

 // Create a new file upload handler
 ServletFileUpload upload = new ServletFileUpload(factory);

 // Parse the request
 List<FileItem> items = upload.parseRequest(req);

 // Process the uploaded items
 for(FileItem item : items) {
     if( ! item.isFormField()) {
         String fieldName = item.getFieldName();
         String fileName = item.getName();
         String itemContentType = item.getContentType();
         boolean isInMemory = item.isInMemory();
         long sizeInBytes = item.getSize();

         // POST the file to the cdn uploader
         postDataRequestToUrl("<the host im uploading too>", "uploadedfile", fileName, item.get());

     } else {
         throw new RuntimeException("Not expecting any form fields");
     }
 }

....

// Post a request to specified URL. Get response as a string.
public static void postDataRequestToUrl(String url, String paramName, String fileName, byte[] requestFileData) throws IOException {
 URLConnection connection=null;

 try{
     String boundary = Long.toHexString(System.currentTimeMillis()); // Just generate some unique random value.
     String charset = "utf-8";

     connection = new URL(url).openConnection();
     connection.setDoOutput(true);
     connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
     PrintWriter writer = null;
     OutputStream output = null;
     try {
         output = connection.getOutputStream();
         writer = new PrintWriter(new OutputStreamWriter(output, charset), true); // true = autoFlush, important!

         // Send binary file.
         writer.println("--" + boundary);
         writer.println("Content-Disposition: form-data; name=\""+paramName+"\"; filename=\"" + fileName + "\"");
         writer.println("Content-Type: " + URLConnection.guessContentTypeFromName(fileName));
         writer.println("Content-Transfer-Encoding: binary");
         writer.println();

         output.write(requestFileData, 0, requestFileData.length);
         output.flush(); // Important! Output cannot be closed. Close of writer will close output as well.

         writer.println(); // Important! Indicates end of binary boundary.

         // End of multipart/form-data.
         writer.println("--" + boundary + "--");
     } finally {
         if (writer != null) writer.close();
         if (output != null) output.close();
     }

     //*  screw the response

     int status = ((HttpURLConnection) connection).getResponseCode();
     logger.info("Status: "+status);
     for (Map.Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) {
         logger.info(header.getKey() + "=" + header.getValue());
     }

 } catch(Throwable e) {
     logger.info("Problem",e);
 } 

}

I can see this code uploading the file, but only after I shutdown the tomcat. This leads me to believe that I’m leaving some sort of connection open.

This worked!

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-16T07:09:50+00:00Added an answer on May 16, 2026 at 7:09 am

    The core API you’d like to use is java.net.URLConnection. This is however pretty low level and verbose. You’d like to learn about the HTTP specifics in detail and take them into account (headers, etcetera). You can find here a related question with lot of examples.

    A more convenient HTTP client API is the Apache Commons HttpComponents Client. You can find an example here.


    Update: as per your update: you should read the response as a character stream, not as a binary stream and attempt to cast a byte to a char. This ain’t going to work. Head to the Gathering HTTP response information part in the linked question with examples. Here’s how it should look like:

    BufferedReader reader = null;
    StringBuilder builder = new StringBuilder();
    
    try {
        reader = new BufferedReader(new InputStreamReader(response, charset));
        for (String line; (line = reader.readLine()) != null;) {
            builder.append(line);
        }
    } finally {
        if (reader != null) try { reader.close(); } catch (IOException logOrIgnore) {}
    }
    
    return builder.toString();
    

    Update 2: as per your second update. Seeing the way how you continue to attampt reading/writing streams, I think it’s high time to learn the basic Java IO 🙂 Well, this part is also answered in the linked question. You would like to use Apache Commons FileUpload to parse a multipart/form-data request in a servlet. How to use it is also described/linked in the linked question. Look at the bottom of the Uploading files chapter. By the way, the content length header would return zero since you are not explicitly setting it (and also cannot do without buffering the entire request in memory).


    Update 3:

    I can see this code uploading the file, but only after I shutdown the tomcat. This leads me to believe that I’m leaving some sort of connection open.

    You need to close the OutputStream with which you wrote the file to the disk. Once again, read the above linked basic Java IO tutorial.


    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 483k
  • Answers 483k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer I was able to find the answer. From the UITableViewDataSource… May 16, 2026 at 7:10 am
  • Editorial Team
    Editorial Team added an answer Modified the template. It was using reflections. May 16, 2026 at 7:10 am
  • Editorial Team
    Editorial Team added an answer I would split the checker and the updater into two… May 16, 2026 at 7:10 am

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.