title: How do I send an image file in a Http POST request? (java)
body: <p>So I'm writing a small app to dump a directory of images into the user's tumblr blog, using their provided API: <a href="http://www.tumblr.com/docs/en/api" rel="nofollow">http://www.tumblr.com/docs/en/api</a></p>
  
  <p>I've gotten plaintext posting to work, but now I need to find out how to send an image file in the POST instead of UTF-8 encoded text, and I'm lost. My code at the moment is returning a 403 forbidden error, as if the username and password were incorrect (they're not), and everything else I try gives me a bad request error. I'd rather not have to use external libraries for this if I can. This is my ImagePost class:</p>
  
  <pre><code>public class ImagePost {
  
  String data = null;
  String enc = "UTF-8";
  String type;
  File img;
  
  public ImagePost(String imgPath, String caption, String tags) throws IOException {
  
      //Construct data
      type = "photo";
      img = new File(imgPath);
  
      data = URLEncoder.encode("email", enc) + "=" + URLEncoder.encode(Main.getEmail(), enc);
      data += "&amp;" + URLEncoder.encode("password", enc) + "=" + URLEncoder.encode(Main.getPassword(), enc);
      data += "&amp;" + URLEncoder.encode("type", enc) + "=" + URLEncoder.encode(type, enc);
      data += "&amp;" + URLEncoder.encode("data", enc) + "=" + img;
      data += "&amp;" + URLEncoder.encode("caption", enc) + "=" + URLEncoder.encode(caption, enc);
      data += "&amp;" + URLEncoder.encode("generator", "UTF-8") + "=" + URLEncoder.encode(Main.getVersion(), "UTF-8");
      data += "&amp;" + URLEncoder.encode("tags", "UTF-8") + "=" + URLEncoder.encode(tags, "UTF-8");
  
  }
  
  public void send() throws IOException {
      // Set up connection
      URL tumblrWrite = new URL("http://www.tumblr.com/api/write");
      HttpURLConnection http = (HttpURLConnection) tumblrWrite.openConnection();
      http.setDoOutput(true);
      http.setRequestMethod("POST");
      http.setRequestProperty("Content-Type", "image/png");
      DataOutputStream dout = new DataOutputStream(http.getOutputStream());
      //OutputStreamWriter out = new OutputStreamWriter(http.getOutputStream());
  
      // Send data
      http.connect();
      dout.writeBytes(data);
      //out.write(data);
      dout.flush();
      System.out.println(http.getResponseCode());
      System.out.println(http.getResponseMessage());
      dout.close();
  }
  }
  </code></pre>