开发者

Java POSTing File Results In HTTP 422

I'm trying to build a small Java app for connecting to an application called CampFire and am running into trouble trying to upload files to the system. The Java code I'm using to upload a file is as follows:

public static String postFile(String requestUri, File f)
{
  debug("Running postFile.");
  logIn();

  debug("Sending File: " + f.getAbsolutePath() + " to " + campFireURL + requestUri);

  URL url;
  URLConnection conn;

  String linebreak = "\r\n";
  String boundary = "**********xxx**********";
  String twoHyphens = "--";


  String result = "";
  String request = twoHyphens + boundary + linebreak +
    "Content-Disposition: form-data; name=\"upload\"; filename=\"" + f.getName() + "\"" + linebreak +
    linebreak +
    "";
  debug("Request: " + request);

  try
  {
   FileInputStream in = new FileInputStream(f);

   auth.resetTries();
   Authenticator.setDefault(auth);

   // Send data
   url = new URL(campFireURL + requestUri);
   conn = url.openConnection();
   conn.setDoOutput(true);
   conn.setDoInput(true);
   conn.setUseCaches(false);

   conn.setRequestProperty("Connection", "Keep-Alive");
   conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

   DataOutputStream wr = new DataOutputStream(conn.getOutputStream());

   wr.writeBytes(request);

   int i;
   while((i = in.read()) != -1)
   {
    wr.write(i);
   }

   wr.writeBytes(linebreak + twoHyphens + boundary + twoHyphens + linebreak);
   wr.flush();

   wr.close();
   in.close();

   result = readFromConnection(conn);
  }
  catch (Exception e)
  {
   debug(e);
   JOptionPane.showMessageDialog(null, "Error running postData: " + e.getMessage(), "HTTP POST Error", JOptionPane.ERROR_MESSAGE);
   die();
  }

  return(result);
 }

开发者_StackOverflow社区When I run this with a real file though, I get the following errors...

Running postFile.
Sending File: /home/myuser/Desktop/blah.png to https://blah.campfirenow.com/room/blah/uploads.xml
Request: --**********xxx**********
Content-Disposition: form-data; name="upload"; filename="blah.png"
Server returned HTTP response code: 422 for URL: blah blah
java.io.IOException: Server returned HTTP response code: 422 for URL: blah blah

Any idea's what I'm doing wrong here? I'm fairly new at Java and am wondering if maybe I missed something obvious?


HTTP error 422 means "Unprocessable Entity". After a quick glance I can spot one mistake: a PNG file is a binary file. You've to add Content-Transfer-Encoding: binary to the header of the part.

If it still doesn't work, then you may find the example in the Uploading files section at the bottom of this answer useful.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜