2013-09-30 2 views
0

я пытаюсь загрузить файл с моей машины на другую машину, используя HttpClientЗагрузка данных с одной машины на другую машину, используя HttpClient

Это мой код:

package com.mxui; 

import java.io.BufferedReader; 
import java.io.File; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.io.UnsupportedEncodingException; 
import org.apache.http.HttpEntity; 
import org.apache.http.HttpResponse; 
import org.apache.http.client.ClientProtocolException; 
import org.apache.http.client.HttpClient; 
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.client.methods.HttpRequestBase; 
import org.apache.http.entity.mime.MultipartEntity; 
import org.apache.http.entity.mime.content.FileBody; 
import org.apache.http.entity.mime.content.StringBody; 
import org.apache.http.impl.client.DefaultHttpClient; 

public class SampleFileUpload 
{ 
    private static String executeRequest(HttpRequestBase requestBase) 
    { 
     String responseString = ""; 
     InputStream responseStream = null; 
     HttpClient client = new DefaultHttpClient(); 
     try{ 
     HttpResponse response = client.execute(requestBase); 
     if(response != null) 
     { 
      HttpEntity responseEntity = response.getEntity(); 
      if (responseEntity != null) 
      { 
       responseStream = responseEntity.getContent(); 
       if (responseStream != null) 
       { 
        BufferedReader br = new BufferedReader (new InputStreamReader (responseStream)); 
        String responseLine = br.readLine(); 
        String tempResponseString = ""; 
        while (responseLine != null) 
        { 
         tempResponseString = tempResponseString + responseLine + System.getProperty("line.separator"); 
         responseLine = br.readLine(); 
        } 
        br.close(); 
        if (tempResponseString.length()>0) 
        { 
         responseString = tempResponseString; 
        } 
       } 
      } 
     } 
     }catch (UnsupportedEncodingException e) 
     { 
      e.printStackTrace(); 
     }catch (ClientProtocolException e) 
     { 
      e.printStackTrace(); 
     }catch (IllegalStateException e) 
     { 
      e.printStackTrace(); 
     }catch (IOException e) 
     { 
      e.printStackTrace(); 
     }finally 
     { 
      if (responseStream != null) 
      { 
       try { 
        responseStream.close(); 
        } catch (IOException e) 
        { 
         e.printStackTrace(); 
        } 
      } 
     } 
     client.getConnectionManager().shutdown(); 
     return responseString; 
    } 

    public String executeMultiPartRequest(String urlString, File file, String fileName, String fileDescription) 
    { 
     HttpPost postRequest = new HttpPost(urlString); 
     try{ 
      MultipartEntity multiPartEntity = new MultipartEntity(); 
      multiPartEntity.addPart("fileDescription", new StringBody(fileDescription != null ? fileDescription : "")); 
      multiPartEntity.addPart("fileName", new StringBody(fileName != null ? fileName : file.getName())); 
      //FileBody fileBody = new FileBody(file, "application/octect-stream"); 
      FileBody fileBody = new FileBody(file, "text/plain"); 
      multiPartEntity.addPart("attachment", fileBody); 
      postRequest.setEntity(multiPartEntity); 
      }catch (UnsupportedEncodingException ex) 
      { 
       ex.printStackTrace(); 
      } 
      return executeRequest(postRequest); 
    } 

    public static void main(String args[]) 
    { 
     SampleFileUpload fileUpload = new SampleFileUpload(); 
     File file = new File ("test.txt"); 
     String response = fileUpload.executeMultiPartRequest("http://192.168.2.21:8080/home/user/Desktop/uploaded-data", file, file.getName(), "File Upload test Hydrangeas.jpg description"); 
     System.out.println("Response : "+response); 
    } 
} 

, но его выполнение и ответ печати пустой, его не выгрузка также , пожалуйста, кто-нибудь может помочь, я пропущу любую вещь. Спасибо.

+0

Как вы настроили сервер? Есть ли прослушивание сервлета на странице http://192.168.2.21:8080/home/user/Desktop/uploaded-data? Попробуйте выполнить печать response.getStatusLine(), чтобы узнать, какие ошибки произошли. – greyfairer

+0

Можете ли вы загрузить этот URL-адрес вручную с помощью формы HTTP-POST? –

+0

нет сервлета, я использую только этот код, и я запускаю tomcat на другой машине. – raajiv

ответ

0

На другой машине также должна быть соответствующая система. Тот, который принимает запрос POST и сохраняет данные в системе.

Apaches Fileupload поможет вам там.

+0

Я понял, что делать, может, коротко проинструктировать меня, что и все, что я должен делать. – raajiv

+0

@raajiv Вам нужно будет почитать о сервлетах. Чтобы начать работу с IDE и создать «новый веб-проект», добавьте Apache Fileupload Jars, затем вы используете среду IDE для создания «нового сервлета», который вы связываете с «/ myservlet». В Servlet вы кладете код Apache Fileupload для получения и сохранения файла. В итоге вы сможете отправить запрос POST на «http: //192.168.2.21: 8080/yourWebproject/myservlet» и должны быть выполнены. –

+0

@raajiv Когда я впервые узнал об этом, мне потребовалось около 3 недель, чтобы понять, что я там делаю, поэтому уделите вам время. –

0
package com.saba.ShRaamVideo; 

import java.io.File; 

import org.apache.http.HttpResponse; 
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.FileBody; 
import org.apache.http.entity.mime.content.StringBody; 
import org.apache.http.impl.client.DefaultHttpClient; 

public class JavaToRest2 
{ 
    public static void main(String args[]) throws Exception 
    { 
     long startTime = System.currentTimeMillis(); 
     doImport(); 
     long endTime = System.currentTimeMillis(); 
     long totalTime = endTime - startTime; 
     System.out.println("totalTime :"+totalTime); 
    } 
    public static void doImport(){ 
     try { 

     File file = new File("C:/Users/arsingh/Desktop/ShRaamData/Content/Scom/Surviving_Sepsis_cloud1.zip") ; 
     //Upload the file 

      executeMultiPartRequest("http://localhost/content/nodejs", 
        file, file.getName(), "File Uploading") ; 
     } catch (Exception e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
    } 
    public static void executeMultiPartRequest(String urlString, File file, String fileName, String fileDescription) throws Exception 
    { 
     HttpClient client = new DefaultHttpClient() ; 
     HttpPost postRequest = new HttpPost (urlString) ; 
     try 
     { 
      //Set various attributes 
      MultipartEntity multiPartEntity = new MultipartEntity() ; 
      // multiPartEntity.addPart("fileDescription", new StringBody(fileDescription != null ? fileDescription : "")) ; 
      // multiPartEntity.addPart("fileName", new StringBody(fileName != null ? fileName : file.getName())) ; 

      // FileBody fileBody = new FileBody(file, "application/octect-stream") ; 
      FileBody fileBody = new FileBody(file) ; 
      //Prepare payload 
      multiPartEntity.addPart("file", 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()); 
      } 
     } 
     catch (Exception ex) 
     { 
      ex.printStackTrace() ; 
     } 
    } 
} 
Смежные вопросы