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 ---本地的文件或图片存储路径。

   

posted @ 2016-01-25 09:33  浪荡小新  阅读(2967)  评论(0编辑  收藏  举报