2011-05-16 4 views
2

그래서 사용자의 텀블러 블로그에 이미지의 디렉토리를 덤프하는 작은 응용 프로그램을 쓰고 있어요, 그들의 제공하는 API를 사용하여 (자바) : http://www.tumblr.com/docs/en/apiHttp POST 요청으로 이미지 파일을 보내려면 어떻게해야합니까?

내가 일하는 일반 텍스트 게시물을받은 적이 있지만 지금은 찾을 필요 UTF-8로 인코딩 된 텍스트 대신 POST에서 이미지 파일을 보내는 방법을 설명하고 있습니다. 현재 내 코드는 403 금지 된 오류를 반환하는 것처럼, 사용자 이름과 암호가 올바르지 않은 경우 (그렇지 않은 경우)와 다른 모든 시도는 잘못된 요청 오류를 발생시킵니다. 필자가 할 수 있다면 외부 라이브러리를 사용할 필요가 없다. 난 당신이 아파치 httpclient 패키지의 MultipartRequestEntity (사용되지 MultipartPostMethod의 후계자)를 사용하는 것이 좋습니다

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

: 이것은 내 ImagePost 클래스입니다. 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(); 
    }   
} 
관련 문제