2013-06-18 18 views
15

Próbuję wysłać obraz do witryny przy użyciu żądań POST protokołu HTTP HTTP.Wysyłanie pliku obrazu przy użyciu połączeń HTTP POST z java

Używam kod bazowy używany tutaj Upload files from Java client to a HTTP server:

To moja modyfikacja:

String urlToConnect = "http://localhost:9000/upload"; 
File fileToUpload = new File("C:\\Users\\joao\\Pictures\\bla.jpg"); 
String boundary = Long.toHexString(System.currentTimeMillis()); // Just generate some unique random value. 

URLConnection connection = new URL(urlToConnect).openConnection(); 
connection.setDoOutput(true); // This sets request method to POST. 
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); 
PrintWriter writer = null; 
try { 
    writer = new PrintWriter(new OutputStreamWriter(connection.getOutputStream())); 
    writer.println("--" + boundary); 
    writer.println("Content-Disposition: form-data; name=\"picture\"; filename=\"bla.jpg\""); 
    writer.println("Content-Type: image/jpeg"); 
    writer.println(); 
    BufferedReader reader = null; 
    try { 
     reader = new BufferedReader(new InputStreamReader(new FileInputStream(fileToUpload))); 
     for (String line; (line = reader.readLine()) != null;) { 
      writer.println(line); 
     } 
    } finally { 
     if (reader != null) try { reader.close(); } catch (IOException logOrIgnore) {} 
    } 
    writer.println("--" + boundary + "--"); 
} finally { 
    if (writer != null) writer.close(); 
} 

// Connection is lazily executed whenever you request any status. 
int responseCode = ((HttpURLConnection) connection).getResponseCode(); 
System.out.println(responseCode); // Should be 200 

dostanę kod 200 odpowiedzi w końcu, ale obraz jest wadliwa, jak w, losowe kolory, które sprawiają, że myślę, że to błąd w kodowaniu znaków. Próbowałem używać UTF-8 jak w oryginalnym przykładzie, ale to właśnie tworzy uszkodzony obraz.

Jestem również w 100% pewien, że to nie jest problem z serwerem, ponieważ mogę używać klientów odpoczynku, takich jak klient zaawansowanego odpoczynku/listonosz i mogą wysyłać obraz bez żadnych problemów.

Czy możesz mi pomóc ustalić, co jest nie tak? Dziękuję Ci.

+0

że należy dodać parametr 'Content-Transfer-Encoding: binary', ponieważ przesyłania powinny być traktowane w postaci binarnej. –

+0

Może problem polegał na tym, że używasz BufferedReader.readLine(), aby uzyskać obraz? Oczywiście widzisz obraz "buggy", ponieważ musisz użyć tylko InputStream.read (bajty, 0, bytes.length), a następnie outputStream.write (bytes) gdzie outputStream jest connection.getOutputStream(); –

Odpowiedz

16
import java.io.File; 
import org.apache.http.HttpEntity; 
import org.apache.http.HttpResponse; 
import org.apache.http.HttpVersion; 
import org.apache.http.client.HttpClient; 
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.entity.mime.MultipartEntity; 
import org.apache.http.entity.mime.content.ContentBody; 
import org.apache.http.entity.mime.content.FileBody; 
import org.apache.http.impl.client.DefaultHttpClient; 
import org.apache.http.params.CoreProtocolPNames; 
import org.apache.http.util.EntityUtils; 


public class PostFile { 
    public static void main(String[] args) throws Exception { 
    HttpClient httpclient = new DefaultHttpClient(); 
    httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); 

    HttpPost httppost = new HttpPost("http://localhost:9000/upload"); 
    File file = new File("C:\\Users\\joao\\Pictures\\bla.jpg""); 

    MultipartEntity mpEntity = new MultipartEntity(); 
    ContentBody cbFile = new FileBody(file, "image/jpeg"); 
    mpEntity.addPart("userfile", cbFile); 


    httppost.setEntity(mpEntity); 
    System.out.println("executing request " + httppost.getRequestLine()); 
    HttpResponse response = httpclient.execute(httppost); 
    HttpEntity resEntity = response.getEntity(); 

    System.out.println(response.getStatusLine()); 
    if (resEntity != null) { 
     System.out.println(EntityUtils.toString(resEntity)); 
    } 
    if (resEntity != null) { 
     resEntity.consumeContent(); 
    } 

    httpclient.getConnectionManager().shutdown(); 
    } 
} 

Użyj kodu HttpClient, aby opracować ten kod. Zawsze lepiej jest używać stabilnych bibliotek innych niż obsługa od zera, chyba że jest coś, co można obsłużyć w niestandardowy sposób.

+0

mam ten błąd: STATUS LINE: HTTP/1.1 200 OK Stampo odpowiedź il: BŁĄD: Plik nie przeniósł correctlyArray ( [usr_img] => Array ( [name] => [FotoProfilo.png typ] => image/jpeg [tmp_name] =>/tmp/phpp170qS [błąd] => 0 [size] => 5327 ) ) – Lele

+0

doskonałym przykładem! Dziękuję bardzo!!! – davs

+1

Uwaga: aby to działało w kompilacji używając czegoś w stylu maven, potrzebujesz zależności zarówno od httpclient, jak i httpmime. –

3

Klasy czytelników/pisarzy są przeznaczone do obsługi danych tekstowych, a obrazy są binarne. Trzeba interpretować swoje pliki jako binarne:

FileChannel   in = new FileInputStream(fileToUpload).getChannel(); 
WritableByteChannel out = Channels.newChannel(connection.getOutputStream()); 

in.transferTo(0, fileToUpload.size(), out) 

Oczywiście, trzeba jeszcze, aby zamknąć wszystkie otwarte zasoby.

+0

Prawdopodobnie masz na myśli WritableByteChannel, bez dodatkowego "e". java.nio.channels.WritableByteChannel –

+0

Oczywiście, dziękuję za uwagę. Naprawiony. – ursa

+0

jeśli typ 'fileToUpload' to' java.io.File', to dlaczego powoduje błąd w 'size()'. – JPG

2

Spróbuj tego:

private DefaultHttpClient mHttpClient; 
Context context; 
public String error = ""; 

//Contrutor para que metodos possam ser usados fora de uma activity 
public HTTPconector(Context context) { 
    this.context = context; 
} 


public HTTPconector() { 
    HttpParams params = new BasicHttpParams(); 
    params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); 
    mHttpClient = new DefaultHttpClient(params); 
} 


public void FileClientPost(String txtUrl, File file){ 
    try 
    { 
     error = ""; 
     HttpPost httppost = new HttpPost(txtUrl); 
     MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); 
     multipartEntity.addPart("Image", new FileBody(file)); 
     httppost.setEntity(multipartEntity); 
     mHttpClient.execute(httppost, new PhotoUploadResponseHandler()); 
    } 
    catch (Exception e) 
    { 
     Log.e(HTTPconector.class.getName(), e.getLocalizedMessage(), e); 
     e.getStackTrace(); 
     error = e.getMessage(); 
    } 
} 

//Verifica se a rede esta disponível 
public boolean isNetworkAvailable() { 
    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); 
    NetworkInfo networkInfo = cm.getActiveNetworkInfo(); 
    // if no network is available networkInfo will be null 
    // otherwise check if we are connected 
    if (networkInfo != null && networkInfo.isConnected()) { 
     return true; 
    } 
    return false; 
} 

public String Get(String txtUrl){ 
    try { 
     URL url = new URL(txtUrl); 
     HttpURLConnection con = (HttpURLConnection) url.openConnection(); 
     con.setReadTimeout(10000); 
     con.setConnectTimeout(15000); 
     con.setRequestMethod("GET"); 
     con.setDoInput(true); 
     con.connect(); 

     return readStream(con.getInputStream()); 

    } catch (ProtocolException e) { 
     e.printStackTrace(); 
     return "ERRO: "+e.getMessage(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
     return "ERRO: "+e.getMessage(); 
    } 
} 


public String Post(String txtUrl){ 
    File image; 

    try { 
     URL url = new URL(txtUrl); 
     HttpURLConnection con = (HttpURLConnection) url.openConnection(); 
     con.setRequestMethod("POST"); 
     con.setDoInput(true); 
     con.setDoOutput(true); 
     con.connect(); 

     //con.getOutputStream().write(("name=" + "aa").getBytes()); 

     return readStream(con.getInputStream()); 
    } catch (ProtocolException e) { 
     e.printStackTrace(); 
     return "ERRO: "+e.getMessage(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
     return "ERRO: "+e.getMessage(); 
    } 
} 


//Usado para fazer conexão com a internet 
public String conectar(String u){ 
    String resultServer = ""; 
    try { 
     URL url = new URL(u); 
     HttpURLConnection con = (HttpURLConnection) url.openConnection(); 
     resultServer = readStream(con.getInputStream()); 
    } catch (Exception e) { 
     e.printStackTrace(); 
     resultServer = "ERRO: "+ e.getMessage(); 
    } 

    Log.i("HTTPMANAGER: ", resultServer); 
    return resultServer; 
} 

//Lê o resultado da conexão 
private String readStream(InputStream in) { 
    String serverResult = ""; 
    BufferedReader reader = null; 
    try { 
     reader = new BufferedReader(new InputStreamReader(in)); 
     String line = ""; 
     while ((line = reader.readLine()) != null) { 
      System.out.println(line); 
     } 

     serverResult = reader.toString(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
     serverResult = "ERRO: "+ e.getMessage(); 
    } finally { 
     if (reader != null) { 
      try { 
       reader.close(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
       serverResult = "ERRO: "+ e.getMessage(); 
      } 
     } 
    } 
    return serverResult; 
} 

private class PhotoUploadResponseHandler implements ResponseHandler<Object> 
{ 
    @Override 
    public Object handleResponse(HttpResponse response)throws ClientProtocolException, IOException { 

     HttpEntity r_entity = response.getEntity(); 
     String responseString = EntityUtils.toString(r_entity); 
     Log.d("UPLOAD", responseString); 
     return null; 
    } 
} 
Powiązane problemy