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) {

    }

    }
  • 相关阅读:
    读书笔记:《与爱因斯坦月球漫步》
    在职工象棋赛上弃子拿下一盘
    桥牌笔记:精准叫牌法摘要
    桥牌笔记:探查牌型分布
    在64位环境下开发程序时常遇到的一个错误:无法加载文件或程序集
    我的记忆图像编码
    【转载】新闻周刊:《2012:31个让你变聪明的方法》
    【转译】希望将来孩子评价父亲的35句话
    桥牌笔记:安全打法,保持将牌控制
    被Html的Button标签耍了一次
  • 原文地址:https://www.cnblogs.com/xiaoxiaojuan/p/9717861.html
Copyright © 2011-2022 走看看