Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Making a POST request to a servlet expecting Multipart data

807607Nov 22 2006 — edited Nov 22 2006
Hello,

I am trying to use the URLConnection and URLEncoder class to make a request to a servlet that expects multipart data.

When the servlet was not multipart expectant, this code worked fine. However, the servlet was upgraded to accept (but not expect) file uploads.

How do I adjust my code below to function with such a servlet that expects multipart data? I tried adding a line to set the content type but I still get the same error.
//begin fetchURL
  public String fetchHTML(String urlArg, String filePathArg, String emailArg, String swissProtIDArg, String seqArg, String notesArg)
  {   
    StringBuffer returnStringBuffer = new StringBuffer();
    
    //try to connect to the url
    try
    { 
	  //connect to the URL & write post data
      URL myUrl = new URL (urlArg);
      URLConnection urlConn = myUrl.openConnection();
      urlConn.setDoOutput(true);
      urlConn.setRequestProperty("Content-Type", "multipart/form-data");
      OutputStreamWriter myOutputStreamWriter = new OutputStreamWriter(urlConn.getOutputStream());
      String keyValuePairs = URLEncoder.encode("email", "UTF-8") + "=" + URLEncoder.encode(emailArg, "UTF-8") +
      			"&" + URLEncoder.encode("swissProtID", "UTF-8") + "=" + URLEncoder.encode(swissProtIDArg, "UTF-8") +
      			"&" + URLEncoder.encode("seq", "UTF-8") + "=" + URLEncoder.encode(seqArg, "UTF-8") +
      			"&" + URLEncoder.encode("notes", "UTF-8") + "=" + URLEncoder.encode(notesArg, "UTF-8");
      myOutputStreamWriter.write(keyValuePairs);
      myOutputStreamWriter.flush();
      
      //get the content from the URL                
      //read each line from the reader and write to the writer
      BufferedReader myBufferedReader = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
      String oneLine = "";
      while ((oneLine = myBufferedReader.readLine()) != null) { returnStringBuffer.append(oneLine); }
      myBufferedReader.close(); 
    }
    catch (Exception e) 
    { 
	  	StringWriter myStringWriter = new StringWriter();
		PrintWriter myPrintWriter = new PrintWriter(myStringWriter);
		e.printStackTrace(myPrintWriter);
		returnStringBuffer.append(myStringWriter.toString()); 
    }
    
    return returnStringBuffer.toString();

  }
The returned error is "Posted content type isn't multipart/form-data".

Can some offer a suggestion?
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Dec 20 2006
Added on Nov 22 2006
1 comment
171 views