Java构建Request请求

前两天在做我们内部系统时,需要我们网腾讯平台上回传数据,当时给的接口是这样的

请求示例:

curl -i "https://api.weixin.qq.com/marketing/user_action_sets/add?version=v1.0&access_token=<ACCESS_TOKEN>" 
-H "Content-Type: application/json" 
-d '{ 
   "type": "WEB", 
   "name": "wxadtest",
   "description": "test"
    }'

当时看见之后,可以猜测出-H的含义,但是,这个-d是什么玩意?传递参数不都是 key:value的形式吗,这个只是一个value啊,该怎么接收啊????
随后赶紧查文章:《cURL 的十种常见用法》
在这里插入图片描述
随后,使用postman来构建这个请求:

在这里插入图片描述

1. 两种方式构建request请求

1.1. RestTemplate
  1. 向后台发送字符串
		JSONObject jsonData = new JSONObject();
        jsonData.put("type","WEB");
        jsonData.put("name",wxadtest);
        jsonData.put("description",test);
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity httpEntity = new HttpEntity(jsonData.toJSONString(),httpHeaders);
        String url="https://api.weixin.qq.com/marketing/user_action_sets/add?version=v1.0&access_token=<ACCESS_TOKEN>"
       	String result= new RestTemplate().postForObject(url,httpEntity,String.class);
  1. 向后台传递文件
    传递多个文件
	    String url = "http://127.0.0.1:8080/test/upload.do";
		String filePath = "C:\\Users\\MikanMu\\Desktop\\test.txt";
 
		RestTemplate rest = new RestTemplate();
		FileSystemResource resource = new FileSystemResource(new File(filePath));
		MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
		param.add("file", resource);
		// 传递多个文件,以此构建 resource 对象, 并依次param.add("files", resource);
		param.add("fileName", "test.txt");
 		String result= rest.postForObject(url, param, String.class);
1.2. HttpPost
  1. 传递字符串
      HttpClient httpClient = new DefaultHttpClient();
      String url ="https://api.weixin.qq.com/marketing/user_action_sets/add?version=v1.0&access_token=<ACCESS_TOKEN>";
      HttpPost httpPost =new HttpPost(url);
      JSONObject jsonData = new JSONObject();
      jsonData.put("type","WEB");
      jsonData.put("name",wxadtest);
      jsonData.put("description",test);
      StringEntity stringEntity = new StringEntity(jsonData.toString(),"utf-8");
      stringEntity.setContentEncoding("utf-8");
      stringEntity.setContentType("application/json");
      httpPost.setEntity(stringEntity);
      LinkedHashMap result=null;
      try {
          HttpResponse httpResponse = httpClient.execute(httpPost);
          org.apache.http.HttpEntity httpEntity =httpResponse.getEntity();
          if(httpEntity!=null){
            String result= EntityUtils.toString(httpEntity, Charset.forName("UTF-8"));
          }
      }catch (Exception e){
         
      }
  1. 传递文件
    HttpClient上传文件传入MultipartFile类型

/**
    * 使用httpclint 发送文件
    * @author: qingfeng
    * @date: 2019-05-27
    * @param file
    *            上传的文件
    * @return 响应结果
    */
   public static String uploadFile(String url ,MultipartFile file,String fileParamName,Map<String,String>headerParams,Map<String,String>otherParams) {
       CloseableHttpClient httpClient = HttpClients.createDefault();
       String result = "";
       try {
           String fileName = file.getOriginalFilename();
           HttpPost httpPost = new HttpPost(url);
           //添加header
           for (Map.Entry<String, String> e : headerParams.entrySet()) {
               httpPost.addHeader(e.getKey(), e.getValue());
           }
           MultipartEntityBuilder builder = MultipartEntityBuilder.create();
           builder.setCharset(Charset.forName("utf-8"));
           builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);//加上此行代码解决返回中文乱码问题
           builder.addBinaryBody(fileParamName, file.getInputStream(), ContentType.MULTIPART_FORM_DATA, fileName);// 文件流
           for (Map.Entry<String, String> e : otherParams.entrySet()) {
               builder.addTextBody(e.getKey(), e.getValue());// 类似浏览器表单提交,对应input的name和value
           }
           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();
           }
       }
       return result;
   }

2. 后台接受参数

//使用如下方式
String value = request.getParameter("key");
//获取不到传递的字符串须使用以下形式
// 获取到stringBuilder后再格式化取参验证
 InputStreamReader isReader = new InputStreamReader(request.getInputStream(), "utf-8");
 BufferedReader bReader = new BufferedReader(isReader);
 StringBuilder stringBuilder = new StringBuilder();
 String result;
 while ((result = bReader.readLine()) != null) {
        stringBuilder.append(result);
 }
 
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值