java http请求 模拟表单上传文件 multipart/form-data 格式

分为两块 一块为之前的 一块是 重新写了之后 删除的注释 方便查看的

这是方便使用 的

public static void main(String[] args) throws Exception {
		String url  ="";
		String pushSynDataWz = pushSynDataWz(null);
		System.out.println(pushSynDataWz);
	}
 public static String postFileMultiPart(String url,Map<String,ContentBody> reqParam,String token) throws Exception{
	        CloseableHttpClient httpclient = HttpClients.createDefault();
	        
	        try {
	            // 创建httpget.    
	            HttpPost post = new HttpPost(url);
//	            post.setHeader("Authorization", "Bearer "+token);
	            //setConnectTimeout:设置连接超时时间,单位毫秒。setConnectionRequestTimeout:设置从connect Manager获取Connection 超时时间,单位毫秒。这个属性是新加的属性,因为目前版本是可以共享连接池的。setSocketTimeout:请求获取数据的超时时间,单位毫秒。 如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用。
	            RequestConfig defaultRequestConfig = RequestConfig.custom().setConnectTimeout(5000).setConnectionRequestTimeout(5000).setSocketTimeout(15000).build();
	            post.setConfig(defaultRequestConfig);
	            
	            System.out.println("executing request " + post.getURI());
	            
	            MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
	        	for(Entry<String,ContentBody> param : reqParam.entrySet()){
	            	multipartEntityBuilder.addPart(param.getKey(), param.getValue());
				}
	            HttpEntity reqEntity = multipartEntityBuilder.build();
	            post.setEntity(reqEntity);

	            // 执行post请求.    
	            CloseableHttpResponse response = httpclient.execute(post);
	            
	            System.out.println("got response");
	            
	            try {  
	                // 获取响应实体    
	                HttpEntity entity = response.getEntity();  
	                //System.out.println("--------------------------------------");  
	                // 打印响应状态    
	                //System.out.println(response.getStatusLine());  
	                if (entity != null) { 
	                	return EntityUtils.toString(entity,Charset.forName("UTF-8"));
	                }
	                //System.out.println("------------------------------------");  
	            } finally {  
	                response.close();
	                
	            }
	        } finally {  
	            // 关闭连接,释放资源    
	            try {  
	                httpclient.close();  
	            } catch (IOException e) {  
	                e.printStackTrace();  
	            }  
	        }
	        return null;  
	    }
	    private static String responseContentToString(HttpResponse response) throws IOException {
	        int statusCode = response.getStatusLine().getStatusCode();
	        if (statusCode == 200) {
	            HttpEntity resEntity = response.getEntity();
	            if (resEntity != null) {
	                String result = EntityUtils.toString(resEntity, "UTF-8");
	                return result;
	            } else {
	                throw new BusinessException("无响应数据");
	            }
	        } else {
	            throw new BusinessException("请求对方失败,返回码:" + statusCode);
	        }
	    }
	    /**
	     * 文件识别
	     * 
	     * @param type   营业执照  102001    开票信息  1000001     身份证 101001  正面   101002  背面
	     * @param fileUrl   识别的图片名称
	     * @return
	     * @throws NoSuchAlgorithmException
	     * @throws Exception
	     */
	    public static String identFile(String type,String fileUrl ) throws NoSuchAlgorithmException, Exception {
	    	Map<String,ContentBody> content = new HashMap<String,ContentBody>();
	    	ContentType create = ContentType.create("multipart/form-data",Charset.forName("UTF-8"));
	    	content.put("app_key", new StringBody(APPKEY, create));
	    	String timestamp = String.valueOf(System.currentTimeMillis()/1000);
	    	String md5Encode = YQTEncryptUtil.md5Encode(APPKEY+"+"+timestamp+"+"+APPSECRET);
	    	content.put("timestamp", new StringBody(timestamp, create));
	    	content.put("token", new StringBody(md5Encode, create));
	    	
	    	content.put("doc_type", new StringBody(type, create));//营业执照  102001
//	    	content.put("doc_type", new StringBody("102001", create));//营业执照  102001
//	    	content.put("doc_type", new StringBody("102001", create));//开票信息  1000001  
//	    	content.put("doc_type", new StringBody("101001,101002,", create));//身份证 101001  正面   101002  背面
//	    	content.put("mode", new StringBody("fetch", create));
//	    	content.put("extract_level", new StringBody("0", create));
	    	content.put("image_url", new StringBody(fileUrl, create));

	    	

//	            URLConnection urlconn = url.openConnection(); // 试图连接并取得返回状态码
//	            urlconn.connect();
//	            HttpURLConnection httpconn = (HttpURLConnection) urlconn;
//	            int HttpResult = httpconn.getResponseCode();
//	            if (HttpResult != HttpURLConnection.HTTP_OK) {
//	                System.out.print("无法连接到");
//	            }
//	            InputStreamReader isReader = new InputStreamReader(urlconn.getInputStream(), "UTF-8");
//	    	content.put("image_file", new FileBody(new File(urlconn.getInputStream())));
	    	
	    
//	    	
	    	String synDataWzUrl = URL + "/v1/docs/fetch";
	    	System.out.println(synDataWzUrl);
	    	String data = null;
	    	
	    	try {
				data = postFileMultiPart(synDataWzUrl, content,null);
			} catch (Exception e) {
				e.printStackTrace();
			}
	    	return data;
	    }
	
	    public static String pushSynDataWz(String token ) throws NoSuchAlgorithmException, Exception {
	    	Map<String,ContentBody> content = new HashMap<String,ContentBody>();
	    	ContentType create = ContentType.create("multipart/form-data",Charset.forName("UTF-8"));
	    	content.put("app_key", new StringBody(APPKEY, create));
	    	String timestamp = String.valueOf(System.currentTimeMillis()/1000);
	    	String md5Encode = YQTEncryptUtil.md5Encode(APPKEY+"+"+timestamp+"+"+APPSECRET);
	    	content.put("timestamp", new StringBody(timestamp, create));
	    	content.put("token", new StringBody(md5Encode, create));
	    	
//	    	content.put("doc_type", new StringBody("102001", create));//营业执照  102001
//	    	content.put("doc_type", new StringBody("102001", create));//开票信息  1000001  
	    	content.put("doc_type", new StringBody("101001,101002,", create));//身份证 101001  正面   101002  背面
//	    	content.put("mode", new StringBody("fetch", create));
//	    	content.put("extract_level", new StringBody("0", create));
//	    	content.put("image_url", new StringBody(url, create));

	    	
	    	
	    	
//	    	
	    	String synDataWzUrl = URL + "/v1/docs/fetch";
	    	System.out.println(synDataWzUrl);
	    	String data = null;
	    	
	    	try {
	    		data = postFileMultiPart(synDataWzUrl, content,token);
	    		
	    	} catch (Exception e) {
	    		e.printStackTrace();
	    	}
	    	return data;
	    }

这是初始版本

package com.jl.net.exmsteel.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import com.jl.net.exmsteel.service.DzjcConnectorService;
import com.jl.net.framework.exception.BusinessException;
import com.jl.net.framework.util.DateUtils;
import com.jl.net.framework.util.HttpsPost;
import com.jl.net.framework.util.SslClient;
import org.apache.commons.lang.StringUtils;
import org.apache.http.Consts;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
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.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

@Service
public class DzjcConnectorServiceImpl implements DzjcConnectorService {

private static final Logger LOGGER = LoggerFactory.getLogger(DzjcConnectorServiceImpl.class);


@Override
public void httpContract(JsonObject jsonObject) {

    String url = "";
    DefaultHttpClient httpClient = null;
    HttpPost post = null;
     
    String s;
    try {
        httpClient = createHttpClient(url, 20 * 1000);

// post = createPost(url, jsonObject);
HttpResponse response = httpClient.execute(post);
s = responseContentToString(response);
} catch (Exception e) {
LOGGER.error(“失败”, e);
}
}

public static DefaultHttpClient createHttpClient(String url, int timeoutMilliSeconds) throws NoSuchAlgorithmException, KeyManagementException {
    Object httpClient;
    if (StringUtils.startsWithIgnoreCase(url, "HTTPS")) {
        httpClient = new SslClient();
    } else {
        httpClient = new DefaultHttpClient();
    }

    ((DefaultHttpClient) httpClient).getParams().setParameter("http.connection.timeout", timeoutMilliSeconds);
    ((DefaultHttpClient) httpClient).getParams().setParameter("http.socket.timeout", timeoutMilliSeconds);
    return (DefaultHttpClient) httpClient;
}


public static HttpPost createPostJson(String url,String token, String content) throws UnsupportedEncodingException {
    HttpPost post = new HttpPost(url);
    post.setHeader("Content-type", "application/json; charset=utf-8");
    post.setHeader("Connection", "Close");

    post.setHeader("Authorization", "Bearer "+token);


    StringEntity entity = new StringEntity(content, "UTF-8");
    entity.setContentEncoding("UTF-8");
    entity.setContentType("application/json");
    post.setEntity(entity);
    return post;
}
public static HttpPost createPostFormData(String url,String token, String content) throws UnsupportedEncodingException {
    HttpPost post = new HttpPost(url);

// post.setHeader(“Content-type”, “application/x-www-form-urlencoded; charset=utf-8”);
post.setHeader(“Content-type”, “multipart/form-data; charset=utf-8”);
post.setHeader(“Connection”, “Close”);

    post.setHeader("Authorization", "Bearer "+token);


    StringEntity entity = new StringEntity(content, "UTF-8");
    entity.setContentEncoding("UTF-8");
    entity.setContentType("multipart/form-data");
    post.setEntity(entity);
    return post;
}
public static String postFileMultiPart(String url,JsonObject content) throws Exception{
    CloseableHttpClient httpclient = HttpClients.createDefault();
    
    try {
        // 创建httpget.    
        HttpPost httppost = new HttpPost(url);
    	
        //setConnectTimeout:设置连接超时时间,单位毫秒。setConnectionRequestTimeout:设置从connect Manager获取Connection 超时时间,单位毫秒。这个属性是新加的属性,因为目前版本是可以共享连接池的。setSocketTimeout:请求获取数据的超时时间,单位毫秒。 如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用。
        RequestConfig defaultRequestConfig = RequestConfig.custom().setConnectTimeout(5000).setConnectionRequestTimeout(5000).setSocketTimeout(15000).build();
        httppost.setConfig(defaultRequestConfig);
        
        System.out.println("executing request " + httppost.getURI());
        
        MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();

// multipartEntityBuilder.addPart(param.getKey(), param.getValue());
multipartEntityBuilder.addBinaryBody(“name=“File”; filename=“123.pdf””, new File(“D:\123.pdf”));//添加文件
multipartEntityBuilder.addTextBody(“Language”, “9”); //添加文本类型参数
HttpEntity reqEntity = multipartEntityBuilder.build();
httppost.setEntity(reqEntity);

        // 执行post请求.    
        CloseableHttpResponse response = httpclient.execute(httppost);
        
        System.out.println("got response");
        
        try {  
            // 获取响应实体    
            HttpEntity entity = response.getEntity();  
            //System.out.println("--------------------------------------");  
            // 打印响应状态    
            //System.out.println(response.getStatusLine());  
            if (entity != null) { 
            	return EntityUtils.toString(entity,Charset.forName("UTF-8"));
            }
            //System.out.println("------------------------------------");  
        } finally {  
            response.close();
            
        }
    } finally {  
        // 关闭连接,释放资源    
        try {  
            httpclient.close();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
    }
    return null;  

}
public static String postFileMultiPart2(String url,Map<String,String> content,String token) throws Exception{
CloseableHttpClient httpclient = HttpClients.createDefault();

    try {
        // 创建httpget.    
        HttpPost post = new HttpPost(url);

// post.setHeader(“Content-type”, “multipart/form-data; charset=utf-8”);
// post.setHeader(“Content-type”, “application/x-www-form-urlencoded; charset=utf-8”);
// post.setHeader(“Connection”, “Close”);

        post.setHeader("Authorization", "Bearer "+token);
        //setConnectTimeout:设置连接超时时间,单位毫秒。setConnectionRequestTimeout:设置从connect Manager获取Connection 超时时间,单位毫秒。这个属性是新加的属性,因为目前版本是可以共享连接池的。setSocketTimeout:请求获取数据的超时时间,单位毫秒。 如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用。
        RequestConfig defaultRequestConfig = RequestConfig.custom().setConnectTimeout(5000).setConnectionRequestTimeout(5000).setSocketTimeout(15000).build();
        post.setConfig(defaultRequestConfig);
        
        System.out.println("executing request " + post.getURI());
        
        MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();

// multipartEntityBuilder.addPart(param.getKey(), param.getValue());
// File file = new File(“D:\123.pdf”);

        multipartEntityBuilder.addBinaryBody("qualityInspection", new File("D:\\123.pdf"));//添加文件

// multipartEntityBuilder.addBinaryBody(“name=qualityInspection; filename=123.pdf”, new File(“D:\123.pdf”));//添加文件
// multipartEntityBuilder.addBinaryBody(“name=qualityInspection”, new File(“D:\123.pdf”));//添加文件
Set keySet = content.keySet();
for (String key : keySet) {
if(StringUtils.equals(key, “qualityInspection”)) {
continue;
}
multipartEntityBuilder.addTextBody(key,content.get(key)); //添加文本类型参数
System.out.println(key+“=====”+content.get(key));
}
HttpEntity reqEntity = multipartEntityBuilder.build();
post.setEntity(reqEntity);

        // 执行post请求.    
        CloseableHttpResponse response = httpclient.execute(post);
        
        System.out.println("got response");
        
        try {  
            // 获取响应实体    
            HttpEntity entity = response.getEntity();  
            //System.out.println("--------------------------------------");  
            // 打印响应状态    
            //System.out.println(response.getStatusLine());  
            if (entity != null) { 
            	return EntityUtils.toString(entity,Charset.forName("UTF-8"));
            }
            //System.out.println("------------------------------------");  
        } finally {  
            response.close();
            
        }
    } finally {  
        // 关闭连接,释放资源    
        try {  
            httpclient.close();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
    }
    return null;  
}
public static String postFileMultiPart3(String url,Map<String,ContentBody> reqParam,String token) throws Exception{
    CloseableHttpClient httpclient = HttpClients.createDefault();
    
    try {
        // 创建httpget.    
        HttpPost post = new HttpPost(url);

// post.setHeader(“Content-type”, “multipart/form-data; charset=utf-8”);
// post.setHeader(“Content-type”, “application/x-www-form-urlencoded; charset=utf-8”);
// post.setHeader(“Connection”, “Close”);

        post.setHeader("Authorization", "Bearer "+token);
        //setConnectTimeout:设置连接超时时间,单位毫秒。setConnectionRequestTimeout:设置从connect Manager获取Connection 超时时间,单位毫秒。这个属性是新加的属性,因为目前版本是可以共享连接池的。setSocketTimeout:请求获取数据的超时时间,单位毫秒。 如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用。
        RequestConfig defaultRequestConfig = RequestConfig.custom().setConnectTimeout(5000).setConnectionRequestTimeout(5000).setSocketTimeout(15000).build();
        post.setConfig(defaultRequestConfig);
        
        System.out.println("executing request " + post.getURI());
        
        MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();

// multipartEntityBuilder.addPart(param.getKey(), param.getValue());
// File file = new File(“D:\123.pdf”);

// multipartEntityBuilder.addBinaryBody(“qualityInspection”, new File(“D:\123.pdf”));//添加文件
// multipartEntityBuilder.addBinaryBody(“name=qualityInspection; filename=123.pdf”, new File(“D:\123.pdf”));//添加文件
for(Entry<String,ContentBody> param : reqParam.entrySet()){
multipartEntityBuilder.addPart(param.getKey(), param.getValue());
}
HttpEntity reqEntity = multipartEntityBuilder.build();
post.setEntity(reqEntity);

        // 执行post请求.    
        CloseableHttpResponse response = httpclient.execute(post);
        
        System.out.println("got response");
        
        try {  
            // 获取响应实体    
            HttpEntity entity = response.getEntity();  
            //System.out.println("--------------------------------------");  
            // 打印响应状态    
            //System.out.println(response.getStatusLine());  
            if (entity != null) { 
            	return EntityUtils.toString(entity,Charset.forName("UTF-8"));
            }
            //System.out.println("------------------------------------");  
        } finally {  
            response.close();
            
        }
    } finally {  
        // 关闭连接,释放资源    
        try {  
            httpclient.close();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
    }
    return null;  
}
private static String responseContentToString(HttpResponse response) throws IOException {
    int statusCode = response.getStatusLine().getStatusCode();
    if (statusCode == 200) {
        HttpEntity resEntity = response.getEntity();
        if (resEntity != null) {
            String result = EntityUtils.toString(resEntity, "UTF-8");
            return result;
        } else {
            throw new BusinessException("无响应数据");
        }
    } else {
        throw new BusinessException("请求对方失败,返回码:" + statusCode);
    }
}

/**
 * 获取Token
 *
 * @return
 */
public static String getToken() {
    String url = URL+"/auth?client=SXJLGTYXGS";
    System.out.println(url);
    DefaultHttpClient httpClient = null;
    String aaa = null;
    String data = null;
    try {
        httpClient = HttpsPost.createHttpClient(url, 20 * 1000);
        HttpGet httpGet = new HttpGet(url);
        HttpResponse response = httpClient.execute(httpGet);
        aaa = responseContentToString(response);
        JSONObject json = JSONObject.parseObject(aaa);
        Object o = json.get("data");
        data = o.toString();

// data = JSONObject.toJSONString(o);
} catch (Exception e) {

    }

    return data;
}
public static String pushBatchAdd(String token ) {
	List<JsonObject> list = new  ArrayList<JsonObject>();
	JsonObject content = new JsonObject();
	content.addProperty("proName", "项目施工一4标段");
	content.addProperty("contractNo", "2020-YW-0014");
	content.addProperty("contractRow", "1");
	content.addProperty("purchaseCompanyName", "sxjl公司");
	content.addProperty("supplierCompanyName", "sxjl公司");
	content.addProperty("varietyCategoryName", "钢材");
	content.addProperty("varietyName", "热轧带肋钢筋");
	content.addProperty("materialInfo", "1");
	content.addProperty("weight", "");
	content.addProperty("price", "1000");
	content.addProperty("num", "10");
	content.addProperty("bargainUnit", "方");
	content.addProperty("totalPrice", "20000");
	content.addProperty("deliveryDate", "2020-07-31 16:00:00");
	content.addProperty("comments", "备注1");
	content.addProperty("specifications", "规格描述");
	content.addProperty("producter", "生产商");
	content.addProperty("sourcesCode", "1");
	
	JsonObject content1 = new JsonObject();
	content1.addProperty("proName", "项目施工一4标段");
	content1.addProperty("contractNo", "2020-YW-0014");
	content1.addProperty("contractRow", "1");
	content1.addProperty("purchaseCompanyName", "sxjl公司");
	content1.addProperty("supplierCompanyName", "sxjl公司");
	content1.addProperty("varietyCategoryName", "钢材");
	content1.addProperty("varietyName", "线材");
	content1.addProperty("materialInfo", "2");
	content1.addProperty("weight", "");
	content1.addProperty("price", "1000");
	content1.addProperty("num", "10");
	content1.addProperty("bargainUnit", "方");
	content1.addProperty("totalPrice", "20000");
	content1.addProperty("deliveryDate", "2020-07-31 16:00:00");
	content1.addProperty("producter", "生产商");
	content1.addProperty("specifications", "规格描述");
	content1.addProperty("comments", "备注2");
	content1.addProperty("sourcesCode", "1");

// DateUtils.format(date, formatStr);
list.add(content);
list.add(content1);
System.out.println(list.toString());
// JsonObject content3 = new JsonObject();
// JSONObject parseObject = JSONObject.parseObject(list.toString());
// System.out.println(parseObject);
String bachAddUrl = URL + “/api/contract/batchAdd”;
System.out.println(bachAddUrl);
DefaultHttpClient httpClient = null;
String aaa = null;
String data = null;
try {
httpClient = HttpsPost.createHttpClient(bachAddUrl, 20 * 1000);
HttpPost createPost = createPostJson(bachAddUrl, token, list.toString());
Header[] headers = createPost.getHeaders(“Authorization”);
System.out.println(createPost.getHeaders(“Authorization”)[0]);
HttpResponse response = httpClient.execute(createPost);
aaa = responseContentToString(response);
System.out.println(aaa);
JSONObject json = JSONObject.parseObject(aaa);
Object o = json.get(“data”);
data = o.toString();
// data = JSONObject.toJSONString(o);
} catch (Exception e) {
e.printStackTrace();
}
return data;
}
public static String pushSynDataWz(String token ) {
JsonObject content = new JsonObject();
content.addProperty(“contractNo”, “2020-YW-0013”);
content.addProperty(“transportNumber”, “2020-YW-0012”);
content.addProperty(“projectName”, “项目施工一标段”);
content.addProperty(“userName”, “sxjl公司”);
content.addProperty(“qualityInspection”, “文件地址”);
content.addProperty(“varietyName”, “热轧带肋钢筋,线材”);
content.addProperty(“materialInfo”, “2”);
content.addProperty(“sourcesCode”, “1”);

	List<JsonObject> list = new  ArrayList<JsonObject>();
	JsonObject content1 = new JsonObject();
	content1.addProperty("certificateNo", "证书编号");
	content1.addProperty("batchNo", "批次号");
	content1.addProperty("slabNo", "板胚号");
	content1.addProperty("material", "材质");
	content1.addProperty("specification", "规格");
	content1.addProperty("weight", "1553");
	content1.addProperty("signNo", "件次号");
	content1.addProperty("yieldStrength", "屈服强度");
	content1.addProperty("tensileStrength", "抗拉强度");
	content1.addProperty("elongation", "伸长率");
	content1.addProperty("bend", "弯曲");
	content1.addProperty("reverseBending", "反向弯曲");
	content1.addProperty("weightDeviation", "重量偏差");
	content1.addProperty("surfaceQuality", "表面质量");
	content1.addProperty("chemicalComposition", "化学成分");
	content1.addProperty("yieldStrengthRatio", "屈强比");
	
	list.add(content1);
	content.addProperty("steels", list.toString());
	
	System.out.println(content.get("steels").toString().replace("\\", ""));
	System.out.println(content.get("contractNo"));
	return token;
}
public static String pushSynDataWz2(String token ) {
	Map<String, String> content = new HashMap<String,String>();
	content.put("contractNo", "2020-YW-0013");

// content.put(“transportNumber”, “2020-YW-0012”);
content.put(“projectName”, “项目施工一二标段”);
content.put(“userName”, “sxjl公司”);
content.put(“qualityInspection”, “文件地址”);
content.put(“varietyName”, “热轧带肋钢筋,线材”);
content.put(“materialInfo”, “2”);
content.put(“sourcesCode”, “1”);

	List<JsonObject> list = new  ArrayList<JsonObject>();
	JsonObject content1 = new JsonObject();
	content1.addProperty("certificateNo", "证书编号");
	content1.addProperty("batchNo", "批次号");
	content1.addProperty("slabNo", "板胚号");
	content1.addProperty("material", "材质");
	content1.addProperty("specification", "规格");
	content1.addProperty("weight", "1553");
	content1.addProperty("signNo", "件次号");
	content1.addProperty("yieldStrength", "屈服强度");
	content1.addProperty("tensileStrength", "抗拉强度");
	content1.addProperty("elongation", "伸长率");
	content1.addProperty("bend", "弯曲");
	content1.addProperty("reverseBending", "反向弯曲");
	content1.addProperty("weightDeviation", "重量偏差");
	content1.addProperty("surfaceQuality", "表面质量");
	content1.addProperty("chemicalComposition", "化学成分");
	content1.addProperty("yieldStrengthRatio", "屈强比");
	content1.addProperty("scanNum", "1");
	
	list.add(content1);
	content.put("steels", list.toString());
	
	System.out.println(content.get("steels").toString().replace("\\", ""));
	System.out.println(content.get("contractNo"));
	String synDataWzUrl = URL + "/api/datawzquality/synDataWz";
	System.out.println(synDataWzUrl);
	String data = null;
	try {
		data = postFileMultiPart2(synDataWzUrl, content,token);
	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	return data;
}
public static String pushSynDataWz3(String token ) {
	Map<String,ContentBody> content = new HashMap<String,ContentBody>();
	ContentType create = ContentType.create("multipart/form-data",Charset.forName("UTF-8"));
	content.put("contractNo", new StringBody("2020-YW-0014", create));
	content.put("transportNumber", new StringBody("2020-YW-0014", create));
	content.put("projectName", new StringBody("项目施工一4标段", create));
	content.put("userName", new StringBody("sxjl公司", create));
	content.put("qualityInspection", new FileBody(new File("D:\\124.pdf")));
	content.put("varietyName", new StringBody("热轧带肋钢筋,线材", create));
	content.put("materialInfo", new StringBody("2", create));
	content.put("sourcesCode", new StringBody("1", create));

//
List list = new ArrayList();
JsonObject content1 = new JsonObject();
content1.addProperty(“certificateNo”, “证书编号”);
content1.addProperty(“batchNo”, “批次号”);
content1.addProperty(“slabNo”, “板胚号”);
content1.addProperty(“material”, “材质”);
content1.addProperty(“specification”, “规格”);
content1.addProperty(“weight”, “1553”);
content1.addProperty(“signNo”, “件次号”);
content1.addProperty(“yieldStrength”, “屈服强度”);
content1.addProperty(“tensileStrength”, “抗拉强度”);
content1.addProperty(“elongation”, “伸长率”);
content1.addProperty(“bend”, “弯曲”);
content1.addProperty(“reverseBending”, “反向弯曲”);
content1.addProperty(“weightDeviation”, “重量偏差”);
content1.addProperty(“surfaceQuality”, “表面质量”);
content1.addProperty(“chemicalComposition”, “化学成分”);
content1.addProperty(“yieldStrengthRatio”, “屈强比”);
content1.addProperty(“scanNum”, “1”);

	list.add(content1);
	content.put("steels", new StringBody(list.toString(), create));
	System.out.println(content.get("steels").toString().replace("\\", ""));
	System.out.println(content.get("contractNo"));
	String synDataWzUrl = URL + "/api/datawzquality/synDataWz";
	System.out.println(synDataWzUrl);
	String data = null;
	try {
		data = postFileMultiPart3(synDataWzUrl, content,token);
	} catch (Exception e) {
		e.printStackTrace();
	}
	return data;
}
private final static String URL = "http://221.192.142.50:8081";
public static void main(String[] args) {
	String token = getToken();
	
	System.out.println(token);

// String pushBatchAdd = pushBatchAdd(token);
// System.out.println(pushBatchAdd);

	//pushSynDataWz2 不能上传文件 原因仍需排查 (初步怀疑 是因为内部自带的格式multipart/form-data  都是用的 ISO_8859_1 编码格式) pushSynDataWz3可以使用
	String pushSynDataWz = pushSynDataWz3(token);

// String pushSynDataWz = pushSynDataWz2(token);
System.out.println(pushSynDataWz);
}
}



借鉴地址:
https://blog.csdn.net/wsdtq123/article/details/78888734

..加上原文地址 怎么搞得我是在直接抄是的

http://blog.csdn.net/xiaojianpitt/article/details/6856536、
这篇文章  我好像知道了 为什么我把类型 放到header会报错了
post.setHeader("Content-type", "multipart/form-data; charset=utf-8");

模拟的是浏览器请求,而浏览器中表单提交的时候 会有boundary=  这样一个属性附加值  ,每个浏览器是不同的,而且每个请求 应该也是不同的  如果我这样 直接设置的话  没有boundary参数   这样会有问题(问题不清楚)
  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值