2013-12-19 3 views
1

Этот вопрос очень похож на How to upload a file using Java HttpClient library working with PHP, но даже MultipartEntity не загружает файл правильно. Вот MWE на стороне клиента:Загрузка файла с использованием библиотеки httpclient apache не работает

import java.io.*; 
import java.util.*; 

import org.apache.http.entity.mime.*; 
import org.apache.http.client.*; 
import org.apache.http.message.*; 
import org.apache.http.*; 
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.impl.client.DefaultHttpClient; 
import org.apache.http.client.entity.UrlEncodedFormEntity; 
import org.apache.http.client.*; 
import org.apache.http.impl.client.*; 
import org.apache.http.entity.mime.content.*; 
import org.apache.http.impl.cookie.BasicClientCookie; 
import org.apache.http.util.EntityUtils; 



// Emulate the post behavior of curl in java except post a string. 
// https://stackoverflow.com/questions/4205980/java-sending-http-parameters-via-post-method-easily 

public class Foo{ 

    static String convertStreamToString(java.io.InputStream is) { 
     java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A"); 
     return s.hasNext() ? s.next() : ""; 
    } 
    // TODO: Fix and test this method. 
    private static void PostData() throws Exception { 
     String url = "http://localhost/index.php"; 
     DefaultHttpClient httpclient = new DefaultHttpClient(); 

     // create the post request. 
     HttpPost httppost = new HttpPost(url); 
     MultipartEntity entity = new MultipartEntity(); 

     ContentBody body = new FileBody(new File("/tmp/HelloWorld"), 
       org.apache.http.entity.ContentType.APPLICATION_OCTET_STREAM); 
     entity.addPart("file", body); 
     httppost.setEntity(entity); 

     // execute request 
     HttpResponse response = httpclient.execute(httppost); 
     HttpEntity resEntity = response.getEntity(); 
     InputStream stream = resEntity.getContent(); 

     System.out.println(response.getStatusLine()); 
     System.out.println(convertStreamToString(stream)); 

    } 
    public static void main(String[] args) throws Exception { 
     PostData(); 
    } 
} 

Содержимое /tmp/HelloWorld' are ПРИВЕТ WORLD`.

Вот что index.php выглядит следующим образом:

<?php 
echo empty($_FILES); 
print_r($_REQUEST); 
print_r($_POST); 
print_r($_GET); 
print_r($_FILES); 
>? 

Выход выглядит так, что, кажется, подразумевает, что содержимое файла отправляются в $_REQUEST и $_POST, а не $_FILES

1 
Array 
(
    [file] => HELLO WORLD 

) 
Array 
(
    [file] => HELLO WORLD 

) 
Array 
(
) 
Array 
(
) 

Мои думаю, что я делаю что-то глупое в клиентском коде, но я не уверен, что это такое.

ответ

2

Я вырыл в исходный код PHP, и, по-видимому, filename требуется на линии Content-Disposition. Поэтому, добавив следующий код от this answer, клиент решает проблему.

FormBodyPart customBodyPart = new FormBodyPart("file", body) { 
      @Override 
      protected void generateContentDisp(final ContentBody body) { 
       StringBuilder buffer = new StringBuilder(); 
       buffer.append("form-data; name=\""); 
       buffer.append(getName()); 
       buffer.append("\""); 
       buffer.append("; filename=\"-\""); 
       addField(MIME.CONTENT_DISPOSITION, buffer.toString()); 
      } 
    }; 
    entity.addPart(customBodyPart); 
Смежные вопросы