2012-08-29 3 views
0

(First Stack Overlflow 질문!) 아래 Perl 예제를 기반으로 Java에서 이에 상응하는 form-data http POST를 코딩하는 데 어려움을 겪고 있습니다. 필자는 와이어 셔크 (WireShark)를 사용하여이 작업 예제를 포착하려고 했으므로 게시되는 XML 데이터를 연구하여 Java 코드를 작성할 수 있지만 주사위는 코딩 할 수 없습니다. 누구든지 아래 코드에서이 XML이 어떻게 생겼는지 알 수 있습니까? 인증 할 수는 있지만 양식 데이터는 Java 코드에서 계속 거부됩니다.이 펄에 해당하는 Java HTTP POST는 무엇입니까?

my $ua = LWP::UserAgent->new(); 
$ua->timeout($MYTIMEOUT); 
$ua->credentials("myweb03:80","mydomain.com",$user, $password); 

my $response = $ua->post($PEPSURL, 'content-type' => 'form-data', 
           Content => { 
           username => $user, 
           prep_id => $prep_id, 
           project => $project, 
           upfile => [ $uploadfile ], 
           discussion => $discussion, 
           silentsave => int($silentFlag) 

      }); 
+3

전혀 XML이 없습니다 : 이 과정에서 텍스트 파일을 업로드, multipart/form-data 포스트를 수행하는 방법의 예입니다. 적어도 자바 개발자로서 나는 그것을 볼 수 없다. –

+1

어떤 XML입니까? 이것은'multipart/form-data'로 인코딩 된 데이터를 포함하는 메시지 본문과 함께'POST' 요청을 제출합니다. – friedo

답변

0

Java에서 post 메소드에는 "built"이 없습니다. 에 따르면

$ua->post($url, $field_name => $value,... Content => \%form) 

:

당신은 LWP의이 양식을 사용하는 :: UserAgent-> 게시물 :는 HttpClient

0

derosast을 하나 만들 수있다, 또는 당신은 특히 Apache's HttpComponents API를 시도 할 수 LWP::UserAgent에 대한 문서 :이 방법은 주어진 $의 URL에 POST 요청을 파견

% 양식 또는 @form가 제공으로 채우기 양식 내용의 키/값 쌍 추가 헤더 및 내용 옵션은 get() 메소드의 경우와 동일합니다.

이 메서드는 HTTP :: Request :: Common에서 POST() 함수를 사용하여 요청을 작성합니다. 양식 콘텐츠 및 기타 고급 기능을 전달하는 방법에 대한 자세한 내용은 HTTP :: Request :: Common을 참조하십시오. HTTP::Request::Common에서

:

POST 'http://www.perl.org/survey.cgi', 
     Content_Type => 'form-data', 
     Content  => [ name => 'Gisle Aas', 
         email => '[email protected]', 
         gender => 'M', 
         born => '1964', 
         init => ["$ENV{HOME}/.profile"], 
         ] 

가 생성이 :

POST http://www.perl.org/survey.cgi 
    Content-Length: 388 
    Content-Type: multipart/form-data; boundary="6G+f" 

    --6G+f 
    Content-Disposition: form-data; name="name" 

    Gisle Aas 
    --6G+f 
    Content-Disposition: form-data; name="email" 

    [email protected] 
    --6G+f 
    Content-Disposition: form-data; name="gender" 

    M 
    --6G+f 
    Content-Disposition: form-data; name="born" 

    1964 
    --6G+f 
    Content-Disposition: form-data; name="init"; filename=".profile" 
    Content-Type: text/plain 

    PATH=/local/perl/bin:$PATH 
    export PATH 

    --6G+f-- 

그래서 다른 포스터는 정확합니다. 형식은 XML이 아닙니다.

희망이 있으면 도움이됩니다.

+0

도움을 청할 때 매우 유익하고 친절합니다. 나는 새로운 희망을 가지고있다. 이 방법을 사용하면 버그 제출 시스템을 자동화하여 매주 동료 시간을 절약 할 수 있습니다. 매우 감사합니다! – derosast

+0

대단히 반갑습니다. 다행 이군! – David

1

http://indiwiz.com/2009/02/11/multi-part-content-upload-in-apache-http-components-http-client/의 주요 코드 예제와 함께이 질문에 답변 해 주신 덕분에 잘 작동했습니다.

package upfile; 

import java.io.*; 
import java.nio.charset.Charset; 
import org.apache.http.*; 
import org.apache.http.auth.AuthScope; 
import org.apache.http.auth.UsernamePasswordCredentials; 
import org.apache.http.client.ClientProtocolException; 
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.entity.mime.MultipartEntity; 
import org.apache.http.entity.mime.content.FileBody; 
import org.apache.http.entity.mime.content.StringBody; 
import org.apache.http.impl.client.DefaultHttpClient; 
import org.apache.http.util.EntityUtils; 

public class Upfile { 
    public static void main(String[] args) throws ClientProtocolException, IOException { 
     DefaultHttpClient httpclient = new DefaultHttpClient(); 
     try { 
      httpclient.getCredentialsProvider().setCredentials(
       new AuthScope("<host>", 80, "<realm>", "basic"), 
       new UsernamePasswordCredentials("<username>", "<password>")); 
      HttpPost httpPost = new HttpPost("<url>"); 
      MultipartEntity entity = new MultipartEntity(); 
      entity.addPart("username", new StringBody("<username>", Charset.forName("UTF-8"))); 
      entity.addParPart("id", new StringBody("86815", Charset.forName("UTF-8"))); 
      entity.addPart("project", new StringBody("GIZMO", Charset.forName("UTF-8"))); 
      entity.addPart("discussion", new StringBody("Discussion text; uploaded via Java!", Charset.forName("UTF-8"))); 
      File f = new File("/Users/sjd/myFile.txt"); 
      FileBody fileBody = new FileBody(f, "text/plain"); 
      entity.addPart("upfile", fileBody); 
      httpPost.setEntity(entity); 
      HttpResponse response = httpclient.execute(httpPost); 

      System.out.println("----------------------------------------"); 
      System.out.println(response.getStatusLine()); 
      if (entity != null) { 
       System.out.println("Response content length: " + 
        entity.getContentLength()); 
       ByteArrayOutputStream outstream = new ByteArrayOutputStream(); 
       response.getEntity().writeTo(outstream); 
       byte[] responseBody = outstream.toByteArray(); 
       System.out.println(responseBody.toString()); 
      } 
      EntityUtils.consume(entity); 
     } finally {   
      httpclient.getConnectionManager().shutdown(); 
     } 
    } 
} 
관련 문제