httpclient post传递json和文件

1. httpclient post传递json并获取远程返回数据

HttpClient 发送请求和接收请求都比较简单,在传递数据的时候需要注意一下,最近刚好用到,亲测完记录一下。httpclient不同版本直接的包差异比较大,我用的版本是 httpclient-4.4.1.jar,如果参数传递json,一共会用到这些jar包:
在这里插入图片描述

1.1 httpclient post 调用端完整代码:
package com.gsoft.modules.odoc.service.impl;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.CloseableHttpResponse;
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.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.junit.Test;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;
import com.gsoft.cos.test.junit.CrystalJUnit4SpringContextTests;

import net.sf.json.JSONObject;
public class DocHessianServiceTest extends CrystalJUnit4SpringContextTests {

	public  String sendHttpPost(String url, String regJson) throws Exception {
		CloseableHttpClient httpClient = HttpClients.createDefault();
		
		HttpPost httpPost = new HttpPost(url);
		httpPost.addHeader("Content-Type", "application/json");
		httpPost.setEntity(new StringEntity(regJson,"UTF-8")); //防止中文乱码

		CloseableHttpResponse response = httpClient.execute(httpPost);
		System.out.println(response.getStatusLine().getStatusCode() + "\n");
		HttpEntity entity = response.getEntity();
		String responseContent = EntityUtils.toString(entity, "UTF-8"); 
		System.out.println(responseContent);

		response.close();
		httpClient.close();
		return responseContent;	
   }
}
1.2 java action 接收json代码:
@RequestMapping(value="/reg/addReceiptReg.edf")
	@ResponseBody
	@BusinessLog(type = BusinessLog.UPDATE, description = "写入登记数据")
	public ResponseMessageDto addReceiptReg(HttpServletRequest request,@RequestBody String regJson){
		Map<String, Object> param = new HashMap<String, Object>();
		try {
			 param = JsonUtils.fromJson(regJson, Map.class);
		} catch (JsonParseException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		regReceiveService.addReceiptReg(param);
		
		return new SuccessDto("提交成功",null);
	}
1.3 测试代码:
@Test
	public  void addReceiptReg(){
		Map<String, Object> map=new HashMap<String, Object>();
		map.put("C_TITLE", "测试远程收文登记接口201811281510");
		map.put("C_RECIVERWORD", "测试");
		map.put("C_RECIVERYEAR", "2018");
		map.put("C_RECIVERNUM", 15);
		map.put("C_RECIVERDOCNUM", "测试〔2018〕15号");
		map.put("C_COMEORGAN", "市政");
		map.put("C_COMEORGCODE", "sz");
		map.put("C_URGENT_LEVEL", "0");//'0':普通 ; '1':加急; '2':特急
		map.put("C_SECRET_GRADE_LEVEL", "0");
		map.put("C_MAINTO", "浙江省财政");
		map.put("C_COPYTO", "临安财政");
		map.put("C_DOCBODY", "");
		map.put("C_DOCBODY_JSON", "");
		map.put("C_TYPE", "4");//来源(1:远程收文 2:内部发送 3:手工登记 4:杭州市政府)
		map.put("C_SENDTIME", new Date());//发送时间为当前时间
		map.put("C_STATUS", "0");//(0:未签收 1: 办理中  2:已签收  3:已转公文 4: 已回收  5:已删除 )'
		map.put("C_DOC_ID", null);//公文id
		map.put("C_DOC_TYPE", "");//公文类型  tyjbj   tywdwlw
		JSONObject jsonObject=JSONObject.fromObject(map);
		System.err.println("json before"+jsonObject.toString());
		try {
			sendHttpPost("http://192.168.1.106:8081/coffice-war/reg/addReceiptReg.edf",jsonObject.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println("登记结束");
	}
2.httpclient post上传文件

上传文件和传递json有部分不同,原理是一样的,直接看代码.

2.1 httpclient post file 代码:
package com.gsoft.modules.odoc.service.impl;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.CloseableHttpResponse;
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.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.junit.Test;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;
import com.gsoft.cos.test.junit.CrystalJUnit4SpringContextTests;

import net.sf.json.JSONObject;
public class DocHessianServiceTest extends CrystalJUnit4SpringContextTests {

	 public String httpClientUploadFile(String url,MultipartFile file) {
	        CloseableHttpClient httpClient = HttpClients.createDefault();
	        String result = "";
	        try {
	            String fileName = file.getOriginalFilename();
	            HttpPost httpPost = new HttpPost(url);
	            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
	            builder.setCharset(Charset.forName("UTF-8"));
	            builder.setMode(HttpMultipartMode.RFC6532);
	            builder.addBinaryBody("file", file.getInputStream(), ContentType.DEFAULT_BINARY, fileName);// 文件流
	            builder.addTextBody("filename", fileName,  ContentType.create("text/plain", Consts.UTF_8));
	            HttpEntity entity = builder.build();
	            httpPost.setEntity(entity);
	            HttpResponse response = httpClient.execute(httpPost);// 执行提交
	            HttpEntity responseEntity = response.getEntity();
	            if (responseEntity != null) {
	                // 将响应内容转换为字符串
	                result = EntityUtils.toString(responseEntity, Charset.forName("UTF-8"));
	            }  
	        } catch (IOException e) {
	            e.printStackTrace();
	        } catch (Exception e) {
	            e.printStackTrace();
	        } finally {
	            try {
	                httpClient.close();
	            } catch (IOException e) {
	                e.printStackTrace();
	            }
	        }
	        System.err.println("result"+result);
	        return result;
	    }
}
2.2 java action代码:
@RequestMapping(value = {"/fileMng/uploadFile.edf"})
	@ResponseBody
	@BusinessLog(module = "文件管理", type = BusinessLog.UPDATE, description = "上传文件")
	public ResponseMessageDto webUploader(HttpServletRequest request,@RequestBody MultipartFile file) throws NoSuchAlgorithmException, IOException {
		Map<String, Object> map=new HashMap<String, Object>();
		map.put("appId", "testapp");
		Map<String, Object> upload = fileManagerService.upload(file, map);
		System.err.println("fileMap"+JsonUtils.toJson(upload));
		return new SuccessDto("文件上传成功!!", upload);
	}
2.3 测试代码
@Test
	public void uploadFlle() { 
		File file = new File("C:/Users/luoyw/Desktop/ES612.docx");
		FileInputStream input = null;
		try {
			input = new FileInputStream(file);
		} catch (FileNotFoundException e2) {
			e2.printStackTrace();
		}
		try {
			MultipartFile multipartFile = new MockMultipartFile("file", file.getName(), "text/plain", input);
			String httpClientUploadFile = httpClientUploadFile("http://192.168.1.106:8081/coffice-war/fileMng/uploadFile.edf",multipartFile);
			JSONObject jsonObject=JSONObject.fromObject(httpClientUploadFile);
			JSONObject obj=JSONObject.fromObject(jsonObject.get("data"));
			System.out.println(obj.get("C_REFERENCE_ID").toString());
			
		} catch (IOException e1) {
			e1.printStackTrace();
		}
	}
  • 5
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值