• POST请求接口实列


    通过响应状态来判断是否读取数据与抛出异常,然后通过判断获取的字节数去读取数据或抛出异常

    /**
    * 发送HttpPost请求
    * @param strURL
    * 服务地址
    * @param params
    * 请求数据
    * @param logIO
    * 是否打印输入输出
    * @return 成功:返回json字符串<br/>
    *
    */

    public static String postJson(String strURL, Object params, boolean logIO) {

    log.info("requestUrl = " + strURL);
    try {
    URL url = new URL(strURL);// 创建连接
    HttpURLConnection connection = (HttpURLConnection) url
    .openConnection();
    connection.setDoOutput(true);
    connection.setDoInput(true);
    connection.setUseCaches(false);
    connection.setInstanceFollowRedirects(true);
    connection.setRequestMethod("POST"); // 设置请求方式
    connection.setRequestProperty("Accept", "application/json"); // 设置接收数据的格式
    connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8"); // 设置发送数据的格式
    connection.setRequestProperty("authorization","xxxxxxxxxxxxxxxx");
    /*
    * if (logIO) {
    * connection.setRequestProperty("X-Xencio-Client-Id",PropUtil.getString(
    * "ecustom", "jz.token.Access")); }
    *///1ae1ea37f00207df4a76e1cde621db93
    connection.connect();
    OutputStreamWriter out = new OutputStreamWriter(
    connection.getOutputStream(), "UTF-8"); // utf-8编码
    String inputJson = new Gson().toJson(params);
    if (logIO) {
    log.info("inputJson = " + inputJson);
    } else {
    log.debug("inputJson = " + inputJson);
    }
    out.append(inputJson);
    out.flush();
    out.close();

    int code = connection.getResponseCode();
    InputStream is = null;
    if (code == 200) {
    is = connection.getInputStream();
    } else {
    is = connection.getErrorStream();
    }

    // 读取响应
    int length = (int) connection.getContentLength();// 获取长度
    if (length != -1) {
    byte[] data = new byte[length];
    byte[] temp = new byte[512];
    int readLen = 0;
    int destPos = 0;
    while ((readLen = is.read(temp)) > 0) {
    System.arraycopy(temp, 0, data, destPos, readLen);
    destPos += readLen;
    }
    String result = new String(data, "UTF-8"); // utf-8编码
    if (logIO) {
    log.info("outputJson = " + result);
    } else {
    log.debug("outputJson = " + result);
    }
    return result;
    }

    } catch (IOException e) {
    log.error("Exception occur when send http post request!", e);
    }
    return "error"; // 自定义错误信息
    }

    测试类

    import org.junit.Test;

    import com.alibaba.fastjson.JSON;
    import com.alibaba.fastjson.JSONObject;

    import ecustom.commons.HttpRequestUtil;
    import ecustom.ecology8.commons.PropUtil;

    @Test

    public void testPostInteface(){

    String resutl=HttpRequestUtil.postJson(url, json,true);

    JSONObject jsonObject= JSON.parseObject(resutl);
    String data = jsonObject.getString("data");
    JSONObject jsondata= JSON.parseObject(data);
    String token = jsondata.getString("tokenid");



    System.out.println("指定值:"+token );

    }

    POST请求通过输入输出流来显示读取数据

    /**
    * 向指定的 URL发送远程POST方法的请求
    * @param url发送请求的 URL
    * @param 入参
    * @return 所代表远程资源的响应结果
    */
    public static JSONObject sendPost(String url, Object params) {
    //PrintWriter out = null;

    DataOutputStream out=null;
    BufferedReader in = null;
    JSONObject jsonObject = null;
    String result = "";
    try {
    URL realUrl = new URL(url);
    // 打开和URL之间的连接
    HttpURLConnection conn = (HttpURLConnection)realUrl.openConnection();
    // 设置通用的请求属性
    conn.setDoOutput(true);
    conn.setDoInput(true);
    conn.setUseCaches(false);
    conn.setInstanceFollowRedirects(true);
    conn.setRequestMethod("POST"); // 设置请求方式
    //设置发送数据的格式
    conn.setRequestProperty("Accept", "application/json");
    //设置请求属性
    conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
    // 发送POST请求必须设置下面的属性
    conn.setDoOutput(true);
    conn.setDoInput(true);
    conn.setUseCaches(false);

    conn.connect();
    // 获取URLConnection对象对应的输出流
    //out = new PrintWriter(conn.getOutputStream());

    out=new DataOutputStream(conn.getOutputStream());


    // 发送请求参数
    String paramsVal = new Gson().toJson(params);
    //out.print(paramsVal);服务器部署出现(操作系统与服务器系统)字符不统一现象
    out.writechars(paremsVal);
    // flush输出流的缓冲
    out.flush();
    // 定义BufferedReader输入流来读取URL的响应
    in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String line = "";
    while ((line = in.readLine()) != null) {
    result += line;
    }
    //将返回结果转换为字符串
    jsonObject = JSONObject.parseObject(result);
    }catch (IOException e) {
    log.error("Exception occur when send http post request!", e);
    }catch (Exception e) {
    throw new RuntimeException("远程通路异常"+e.toString());

    }
    // 使用finally块来关闭输出流、输入流
    finally {
    try {
    if (out != null) {
    out.close();
    }
    if (in != null) {
    in.close();
    }
    } catch (IOException ex) {
    ex.printStackTrace();
    }
    }
    return jsonObject;
    }

    学着把生活的苦酒当成饮料一样慢慢品尝, 不论生命经过多少委屈和艰辛, 我们总是以一个朝气蓬勃的面孔, 醒来在每一个早上。
  • 相关阅读:
    【转】MFC中png格式图片贴图的实现
    【转】Windows 中不规则窗体的编程实现
    【转】MFC添加背景图片方法的三种方法
    【转】mfc win7获得管理员权限 使用WIN7风格 使用当前系统风格
    【转】双缓冲讲解及界面贴图
    【转】[内核/驱动]驱动中获取进程全路径和注册表全路径
    【转】Visual C++中DDB与DIB位图编程全攻略(转)
    【转】vs2010中添加splashScreen
    【转】一个在内存里搜索QQ号码的源码,源自看雪论坛
    输出JSON
  • 原文地址:https://www.cnblogs.com/yhm9/p/11360831.html
Copyright © 2020-2023  润新知