java模擬http請求上傳文件,基於Apache的httpclient


1.依賴

  模擬http端的請求需要依賴Apache的httpclient,需要第三方JSON支持,項目中添加

     <dependency>
            <groupId>org.apache</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.1.2</version>
        </dependency>


<dependency>
   <groupId>org.apache</groupId>
   <artifactId>httpclient</artifactId>
   <version>4.1.2</version>
</dependency>

 

2.源碼

import org.apache.commons.httpclient.HttpStatus;
import org.apache.http.HttpEntity;
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.InputStreamBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by Administrator on 2016/1/19.
 */
public class FileUploadTest {

    public static String upload(String url,String filePath){
        String fdfsPath = "";
        try {
            HttpClient httpclient = new DefaultHttpClient();

//            HttpPost httppost = new HttpPost("http://127.0.0.1:8082/fileUpload.action");//請求格式
            HttpPost httppost = new HttpPost(url);
            File file = new File(filePath);
            String name = file.getName();
            InputStream in = new FileInputStream(file);
            MultipartEntity reqEntity = new MultipartEntity();
            InputStreamBody inputStreamBody = new InputStreamBody(in,name);
            StringBody fileNam = new StringBody(name);

            reqEntity.addPart("uploadFile", inputStreamBody);
            reqEntity.addPart("uploadFileName", fileNam);

            httppost.setEntity(reqEntity);
            HttpResponse response = httpclient.execute(httppost);
            int statusCode = response.getStatusLine().getStatusCode();

            if(statusCode == HttpStatus.SC_OK){

//                System.out.println("服務器正常響應.....");
                HttpEntity resEntity = response.getEntity();
                JSONObject json = new JSONObject(EntityUtils.toString(resEntity).toString());


                System.out.println(json.getString("returnResult"));
//                System.out.println(EntityUtils.toString(resEntity));//httpclient自帶的工具類讀取返回數據
//                System.out.println(resEntity.getContent());

                EntityUtils.consume(resEntity);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

  
}

3.解析

  上傳參數:URL--上傳的服務器端接口請求;filePath ---本地的文件或圖片存儲路徑。

   


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM