2011-05-16 83 views
2

所以我寫一個小程序來轉儲映像到用戶的tumblr博客的目錄中,使用其提供的API:http://www.tumblr.com/docs/en/api如何在Http POST請求中發送圖像文件? (JAVA)

我已經得到明文張貼工作,但現在我需要找到了解如何在POST中發送圖像文件而不是UTF-8編碼文本,並且我迷路了。我的代碼此刻正在返回一個403禁止的錯誤,就好像用戶名和密碼不正確(他們不是),而我嘗試的其他所有內容都會給我一個錯誤的請求錯誤。如果可以的話,我寧願不必爲此使用外部庫。這是我的ImagePost類:

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 += "&" + URLEncoder.encode("password", enc) + "=" + URLEncoder.encode(Main.getPassword(), enc); 
    data += "&" + URLEncoder.encode("type", enc) + "=" + URLEncoder.encode(type, enc); 
    data += "&" + URLEncoder.encode("data", enc) + "=" + img; 
    data += "&" + URLEncoder.encode("caption", enc) + "=" + URLEncoder.encode(caption, enc); 
    data += "&" + URLEncoder.encode("generator", "UTF-8") + "=" + URLEncoder.encode(Main.getVersion(), "UTF-8"); 
    data += "&" + 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(); 
} 
} 

回答

1

我建議你使用MultipartRequestEntity(不建議使用MultipartPostMethod的繼任者)在Apache httpclient包。通過MultipartRequestEntity,您可以發送包含文件的多部分POST請求。示例如下:

public static void postData(String urlString, String filePath) { 

    log.info("postData"); 
    try { 
     File f = new File(filePath); 
     PostMethod postMessage = new PostMethod(urlString); 
     Part[] parts = { 
       new StringPart("param_name", "value"), 
       new FilePart(f.getName(), f) 
     }; 
     postMessage.setRequestEntity(new MultipartRequestEntity(parts, postMessage.getParams())); 
     HttpClient client = new HttpClient(); 

     int status = client.executeMethod(postMessage); 
    } catch (HttpException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    }   
}