1. 程式人生 > >Java 後臺POST模擬檔案上傳

Java 後臺POST模擬檔案上傳

概述

  廢話不多說,直接擼程式碼

程式碼

  1、引入Maven包

<dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpmime</artifactId>
            <version>4.5
</version> </dependency>

     2、編寫Java程式碼

//引入Java包
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
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 static String FilePost(String url,File value) throws Exception { String BOUNDARY = java.util.UUID.randomUUID().toString(); MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, "--------------------"+BOUNDARY, Charset.defaultCharset());
//multipartEntity.addPart("key",new StringBody("123456",Charset.forName("UTF-8"))); //multipartEntity.addPart("from",new StringBody("cw",Charset.forName("UTF-8"))); multipartEntity.addPart("image_binary", new FileBody(value)); //InputStream inputStream=new FileInputStream(value);; //inputStream=new ByteArrayInputStream("字串轉輸入流".getBytes(Charset.forName("UTF-8"))); //inputStream= IOUtil.newInputStream(ByteBuffer.wrap("字串".getBytes())); //multipartEntity.addPart("image_binary",new InputStreamBody(inputStream,"1.jpg")); HttpPost request = new HttpPost(url); request.setEntity(multipartEntity); request.addHeader("Content-Type", "multipart/form-data; boundary=--------------------"+BOUNDARY); //request.addHeader("Content-Type","image/jpeg"); //視情況而定 DefaultHttpClient httpClient = new DefaultHttpClient(); HttpResponse response = httpClient.execute(request); InputStream is = response.getEntity().getContent(); BufferedReader in = new BufferedReader(new InputStreamReader(is)); StringBuffer buffer = new StringBuffer(); String line = ""; while ((line = in.readLine()) != null) { buffer.append(line); } System.out.println("傳送訊息收到的返回:"+buffer.toString()); return buffer.toString(); } public static void main(String[] args) throws Exception { File file=new File("F:\\test\\test\\1.jpg"); String Result=FilePost("http://www.baidu.com/ocr/v2/general_ex",file); }