HttpClient传递多文件&正常参数

记一对接口,实现多文件&常用参数的发起与接收。无业务场景,so不需要前言,贴接口发起端和接口接收端代码

  • 发起
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Charsets;
import com.google.common.hash.Hashing;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.ParseException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 *
 * @author <a href="mailto:just_szl@hotmail.com"> Geray</a>
 * @version 1.0,2012-6-12
 */
public class HttpPostfile_push {

    //file1与file2在同一个文件夹下 filepath是该文件夹指定的路径
    public void SubmitPost(String url,String filename1,String filename2, String filepath){

        HttpClient httpclient = new DefaultHttpClient();

        try {

            HttpPost httpPost = new HttpPost(url);

            FileBody bin = new FileBody(new File(filepath + File.separator + filename1));
            FileBody bin2 = new FileBody(new File(filepath + File.separator + filename2));


            MultipartEntityBuilder reqEntity = MultipartEntityBuilder.create();

            reqEntity.addPart("vehicle_license", bin);//file1为请求后台的File upload;属性
            reqEntity.addPart("vehicle_num0", bin2);//file2为请求后台的File upload;属性

            //接口常规参数开始-----------------------------------------
            Map<String, String> params = new HashMap<>();
            params.put("timestamp", String.valueOf(System.currentTimeMillis()));
            Map<String,Object> map = new HashMap<>();
            map.put("taskNo","XIA2018072712528");
            map.put("vehicleTime", System.currentTimeMillis());  //新增到港时间
            String data = JSONObject.toJSON(map).toString();

            String appsecret = "6e26d75edfde16828fb15f484bed2121";
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            String timestamp = format.format(new Date());
            String md5 = appsecret + "data" + data  + "timestamp" + timestamp;
            String digest = (Hashing.md5().hashString(md5, Charsets.UTF_8)).toString().toUpperCase();


            Map<String, String> map01 = new HashMap<String, String>();
            map01.put("timestamp", timestamp);
            map01.put("sign", digest);
            map01.put("data", data);

            StringBody verification = new StringBody(JSON.toJSONString(map01));
            //接口常规参数结束------------------------------------------------------

            reqEntity.addPart("verification", verification);//filename1为请求后台的普通参数;属性

            HttpEntity httpEntity = reqEntity.build();
            httpPost.setEntity(httpEntity);

            HttpResponse response = httpclient.execute(httpPost);

            int statusCode = response.getStatusLine().getStatusCode();

            if(statusCode == HttpStatus.SC_OK){
                System.out.println("服务器正常响应.....");
                HttpEntity resEntity = response.getEntity();
                System.out.println(EntityUtils.toString(resEntity));//httpclient自带的工具类读取返回数据
                EntityUtils.consume(resEntity);
            }
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                httpclient.getConnectionManager().shutdown();
            } catch (Exception ignore) {
            }
        }
    }

    /**
     * @param args
     */
    public static void main(String[] args) {

        HttpPostfile_push httpPostArgumentTest2 = new HttpPostfile_push();

        httpPostArgumentTest2.SubmitPost("http://127.0.0.1:80/li/yang",
                "psb.jpg","psb.jpg","D://test");

    }

}
  • 接收端
import com.ane56.util.ApplicationContextUtil;
import org.springframework.stereotype.Controller;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * Created by liyang on 2018/8/2.
 */
@Controller
@RequestMapping("li")
public class HttpPostfile_receive{

    @RequestMapping("yang")
    public void kkk(HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("text/html;charset=UTF-8");

        //强转request
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        //获取文件map
        Map<String, MultipartFile> multipartFileMap = multipartRequest.getFileMap();
        //遍历map获取key,file
        Iterator<Map.Entry<String, MultipartFile>> it = multipartFileMap.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, MultipartFile> entry = it.next();
            System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
        }

        //获取接口基本参数
        String verification = multipartRequest.getParameter("verification");
        System.out.println(verification);
    }
}

ps:-------------------------------------------------分割线有这么长-----------------------------------------------------------------------

贴一个关于接口发起端的比较有用的帖子     我是超链接   ,怕被删除代码贴一遍

方法一:使用 org.apache.commons.httpclient;的HttpClient
  • 具体代码:
  • public Map<String, Object> officialOcrUpload(String filePath) {
            Map<String, Object> reContent = new HashMap<>();
            String soapResponseInfo = "";
            File targeFile = new File(filePath);
            HttpClient httpClient = new HttpClient();
            PostMethod postMethod = new PostMethod(OFFICIAL_ENDPOINT+"?bizType=tm");
            int state = 500;
            try {
                FilePart filePart = new FilePart(targeFile.getName(), targeFile);
                filePart.setContentType("multipart/form-data");
                filePart.setName("file");
                Part[] parts = {filePart};
    
                postMethod.setRequestEntity(new MultipartRequestEntity(parts, postMethod.getParams()));
                httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(Integer.valueOf(OFFICIAL_TIMEOUT));//设置连接超时
                state = httpClient.executeMethod(postMethod);
                if (state == HttpStatus.SC_OK) {
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(postMethod.getResponseBodyAsStream(), "utf-8"));
                    String responseLine = "";
                    while((responseLine = bufferedReader.readLine()) != null){
                        soapResponseInfo += responseLine;
                    }
                }
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (HttpException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } finally {
                reContent.put("status", state);
                reContent.put("body", soapResponseInfo);
                postMethod.releaseConnection();
                if (state == HttpStatus.SC_OK) {
                    reContent = queryOfficalDoc(soapResponseInfo);
                }
            }
            return reContent;
        }
    方法二:使用org.apache.http.impl.client;的HttpClient
  • maven中引用的jar包 
    下载路径:http://download.csdn.net/download/lyltiger/10042961
        <dependency>
          <groupId>org.apache.httpcomponents</groupId>
          <artifactId>httpmime</artifactId>
          <version>4.3</version>
        </dependency>

        <dependency>
          <groupId>org.apache.httpcomponents</groupId>
          <artifactId>httpcore</artifactId>
          <version>4.4.6</version>
        </dependency>
  • 具体代码
public String officialFileUpload(String filepath){
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(OFFICIAL_ENDPOINT+"?bizType=tm");
        String result = "";
        try {
            FileBody bin = new FileBody(new File(filepath));
            MultipartEntityBuilder reqEntity = MultipartEntityBuilder.create();
            reqEntity.addPart("file", bin);
            HttpEntity httpEntity = reqEntity.build();
            httpPost.setEntity(httpEntity);
            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity responseEntity = response.getEntity();
            if (responseEntity != null) {
                result = EntityUtils.toString(responseEntity, Charset.forName("UTF-8"));
            }
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            httpPost.releaseConnection();
        }
        return result;
    }

 

转载于:https://my.oschina.net/ytliyang/blog/1921648

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值