1

我正在使用下面的 html 来调用我的服务器 api(rest) 之一

<html>

    <body>
        <form method="post" action="http://localhost:8080/service/uploadFile" enctype="multipart/form-data">
            <input type="file" name="file"/>
            <input type="submit"/>
            <input type="hidden" name="smallSize" value="50x50">
        </form>
    </body>
</html>

如何使用 java 方法调用此 api?

4

2 回答 2

4

可能以下几行可以帮助您。我正在使用 Apache Http api。

HttpClient client = new DefaultHttpClient();
    client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);     
    HttpPost    post   = new HttpPost( "http://localhost:8080/service/uploadFile"));
    MultipartEntity entity = new MultipartEntity( HttpMultipartMode.BROWSER_COMPATIBLE );
    StringBody size= new StringBody("50x50");
    entity.addPart("smallSize", size);
    entity.addPart("file", new FileBody(new File("D:/abc.txt") ));
    post.setEntity(entity);

    HttpResponse response = client.execute(post);
    String responseFromServer = EntityUtils.toString(response.getEntity(), "UTF-8" );
    client.getConnectionManager().shutdown();
    System.out.println("response from server: "+responseFromServer);

根据您的请求类型,在哪里HttpPost和类可用。HttpGet对于发送文件,我们需要使用MultipartEntity类。如果您想发送其他表单字段以及您FileBody喜欢的任何元数据,您可以使用StringBody.

我希望这可以帮助你一点。:)

于 2013-05-17T09:02:01.403 回答
0

您可以使用套接字来模拟 POST 请求,该套接字在端口 80 上使用该表单的地址

    String data = URLEncoder.encode("key1", "UTF-8") + "=" + URLEncoder.encode("value1", "UTF-8");

    Socket socket = new Socket("127.0.0.1", 80);

    String path = "/servlet";
    BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF8"));
    wr.write("POST " + path + " HTTP/1.0\r\n");
    wr.write("Content-Length: " + data.length() + "\r\n");
    wr.write("Content-Type: application/x-www-form-urlencoded\r\n");
    wr.write("\r\n");

    wr.write(data);
    wr.flush();

    BufferedReader rd = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    String line;
    while ((line = rd.readLine()) != null) {
      System.out.println(line);
    }
    wr.close();
    rd.close();

示例取自这里

于 2013-05-17T08:47:07.113 回答