1

我正在尝试使用以下代码将文件作为带有 Java 的 POST 数组的一部分发布到远程服务器:

public void executeMultiPartRequest(String urlString, File file, String fileName, String login, String password, String project) throws Exception 
{
    RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(30 * 1000).build();
    HttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build();
    HttpPost postRequest = new HttpPost (urlString) ;

    try
    {
        //Set various attributes 
        MultipartEntity multiPartEntity = new MultipartEntity () ;
        multiPartEntity.addPart("login", new StringBody(login != null ? login : "")) ;
        multiPartEntity.addPart("password", new StringBody(password != null ? password : "")) ;
        multiPartEntity.addPart("project", new StringBody(project != null ? project : "")) ;
        multiPartEntity.addPart("fileName", new StringBody(fileName != null ? fileName : file.getName())) ;

        FileBody fileBody = new FileBody(file, "image/jpeg") ;
        //Prepare payload
        multiPartEntity.addPart("attachment", fileBody) ;

        //Set to request body
        postRequest.setEntity(multiPartEntity) ;

        //Send request
        HttpResponse response = client.execute(postRequest) ;

        //Verify response if any
        if (response != null)
        {
            System.out.println(response.getStatusLine().getStatusCode());
            HttpEntity resEntity = response.getEntity();

            System.out.println(response.getStatusLine());
            if (resEntity != null) {
              System.out.println(EntityUtils.toString(resEntity));
            }
            if (resEntity != null) {
              resEntity.consumeContent();
            }
            client.getConnectionManager().shutdown();
        }
    }
    catch (Exception ex)
    {
        System.err.println(ex);
        // returns null as the cause is nonexistent or unknown.
        System.err.println("Cause = " + ex.getCause());
    }
}

使用localhost时一切正常,我在 post 数组中获取了我的文件。然而,当使用远程服务器时,$_post['attachment']显示为空,但文件被保存为始终相同的四个字节的西里尔文文本。我是一个 Java 新手,只是想让这个小部分与我的 PHP 服务器端的东西相提并论。为什么会这样?可能是客户端没有时间正确发送数据,还是服务器不接受它的可能性更大?处理请求的代码在localhost远程服务器上是相似的。

4

0 回答 0