什么是Java相当于这个Perl http POST

时间:2012-08-29 05:43:54

标签: java perl http post

(First Stack Overlflow问题!) 基于下面的Perl示例,我很难用Java编写等效的表单数据http POST。我甚至使用WireShark来尝试捕获这个工作示例,这样我就可以研究发布的XML数据,这样我就可以用Java编写代码,但没有骰子。有谁知道下面代码中的这个XML会是什么样子?我可以正常验证,但表单数据在我的Java代码中一直被拒绝。

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 个答案:

答案 0 :(得分:1)

感谢那些回答这个问题的人以及来自http://indiwiz.com/2009/02/11/multi-part-content-upload-in-apache-http-components-http-client/的关键代码示例。 这是一个如何执行multipart / form-data帖子,在此过程中上传文本文件的示例:

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();
        }
    }
}

答案 1 :(得分:0)

Java中的post方法中没有“内置”。您可以构建一个,或者您可以尝试使用Apache's HttpComponents API,尤其是HttpClient

答案 2 :(得分:0)

derosast:

您正在使用此形式的LWP :: UserAgent-&gt;帖子:

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

根据LWP::UserAgent的文档:

  

此方法将使用%form在给定的$ 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 => 'gisle@aas.no',
                         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"

  gisle@aas.no
  --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。

希望这有用。