zoukankan      html  css  js  c++  java
  • restTemplate 的用法

     
    JSONObject json = new JSONObject();
    json.put("mid", mid);
    json.put("tid", tid);
     
     //调用普通接口
    HttpURLConnection httpURLConnection = null;
    BufferedReader ino = null;
    PrintWriter out = null;
    try {
    URL url = new URL(APIurl);
    httpURLConnection = (HttpURLConnection) url.openConnection();
    httpURLConnection.setRequestMethod("POST");
    httpURLConnection.setDoInput(true);
    httpURLConnection.setDoOutput(true);
    httpURLConnection.setRequestProperty("Content_Type","application/json");
    httpURLConnection.setRequestProperty("Accept_Charset","UTF-8");
    httpURLConnection.setRequestProperty("contentType","UTF-8");
    //发送POST请求参数
    out = new PrintWriter(httpURLConnection.getOutputStream());
    // out = new OutputStreamWriter(httpURLConnection.getOutputStream(),"utf-8");
    out.write(strReqJsonStr);
    // out.println(strReqJsonStr);
    out.flush();
    //读取响应
    if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
    StringBuffer content = new StringBuffer();
    String tempStr = null;
    ino = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
    while ((tempStr=ino.readLine()) != null){
    content.append(tempStr);
    }
    System.out.println("content:"+content.toString());
    //转换成json对象
    JSONObject respJson = JSON.parseObject(content.toString());
    String resultCode = respJson.getString("errCode");
    if("SUCCESS".equals(resultCode)){
    //成功继续走下面逻辑
    }else{

    //失败
    }

    }
    return null;

    } catch (RestClientException e) {
    logger.error("调用银商接口出现异常", e.toString() );
    return null;
    }

    RestTemplate 方法实现
    private final RestTemplate restTemplate;

    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.add("Content-Type", "application/json;charset=UTF-8");
    HttpEntity<String> httpEntity = new HttpEntity<>(JSON.toJSONString(paramsMap), httpHeaders);
    ResponseEntity<String> response = restTemplate.exchange(APIurl, POST, httpEntity, String.class);
    if (response.getStatusCode() == HttpStatus.OK) {
    JSONObject result = JSON.parseObject(response.getBody());
    if (result.getInteger("code") == 200) {

    }

    }
  • 相关阅读:
    python内置模块argparse的使用
    pyqt5中通过pycharm配置designer(win和mac都适用,修改下designer目录路径即可)
    初始pyqt5
    pyqt5学习示例
    python中partial用法
    python中操作csv
    python模块imghdr-----推测图像类型
    portainer docker可视化工具
    靠着这份面试手册成功斩获99家BAT大厂offer
    redis事物有一致性吗?
  • 原文地址:https://www.cnblogs.com/xiaoxiaojuan/p/9717861.html
Copyright © 2011-2022 走看看