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

ローカルホストで作業するとすべてうまくいき、ポスト配列にファイルを取得します。しかし、リモート サーバーを使用する場合、$_post['attachment']は空として表示されますが、ファイルは常に同一の 4 バイトのキリル文字として保存されます。私はJavaの完全な初心者であり、この小さな部分を私のPHPサーバー側のものと同等に動作させようとしています. なぜこうなった?クライアントがデータを適切に送信する時間がないのか、それともサーバーがデータを受け入れていない可能性が高いのでしょうか? リクエストを処理するコードは、 localhostリモート サーバーで似ています。

4

0 に答える 0