Advertisement
Armandobs14

Upload de arquivos em Java

Feb 13th, 2016
326
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.76 KB | None | 0 0
  1. package br.com.boamoradia.code;
  2.  
  3. import java.io.File;
  4. import java.io.FileInputStream;
  5. import java.io.FileNotFoundException;
  6. import java.io.IOException;
  7.  
  8. import javax.imageio.stream.FileImageInputStream;
  9.  
  10. import org.apache.http.HttpEntity;
  11. import org.apache.http.HttpResponse;
  12. import org.apache.http.client.ClientProtocolException;
  13. import org.apache.http.client.HttpClient;
  14. import org.apache.http.client.methods.HttpGet;
  15. import org.apache.http.client.methods.HttpPost;
  16. import org.apache.http.entity.ContentType;
  17. import org.apache.http.entity.InputStreamEntity;
  18. import org.apache.http.entity.mime.MultipartEntityBuilder;
  19. import org.apache.http.impl.client.BasicResponseHandler;
  20. import org.apache.http.impl.client.DefaultHttpClient;
  21.  
  22. public class Main {
  23.     public static void main(String[] args) {
  24.         Main m = new Main();
  25.         try {
  26.             m.test();
  27.         } catch (ClientProtocolException e) {
  28.             System.out.println("PROTOCOL ERROR:");
  29.             e.printStackTrace();
  30.         } catch (IOException e) {
  31.             System.out.println("IO ERROR:");
  32.             e.printStackTrace();
  33.         }
  34.     }
  35.    
  36.     public void test() throws ClientProtocolException, IOException{
  37.         String url = "http://localhost";
  38.         File f = new File("/home/armando/Downloads/inteligências.txt");
  39.        
  40.         HttpClient client = new DefaultHttpClient();
  41.         //HttpGet request = new HttpGet(url);
  42.         HttpPost request = new HttpPost(url);
  43.        
  44.         MultipartEntityBuilder b = MultipartEntityBuilder.create();
  45.         b.addBinaryBody("file",f,ContentType.APPLICATION_OCTET_STREAM,"file.ext");
  46.         //b.addTextBody("name","armando");
  47.         HttpEntity ett = b.build();
  48.        
  49.         request.setEntity(ett);
  50.         HttpResponse response = client.execute(request);
  51.         String responseString = new BasicResponseHandler().handleResponse(response);
  52.         System.out.println(responseString);
  53.        
  54.     }
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement