• 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;
    }

    学着把生活的苦酒当成饮料一样慢慢品尝, 不论生命经过多少委屈和艰辛, 我们总是以一个朝气蓬勃的面孔, 醒来在每一个早上。
  • 相关阅读:
    apache安装错误error: APR not found解决办法
    (总结)Nginx配置文件nginx.conf中文详解
    多级反向代理下,Java获取请求客户端的真实IP地址多中方法整合
    x-forwarded-for的深度挖掘
    hashcode与字符串
    千万不要误用 java 中的 HashCode 方法
    浅谈Java中的hashcode方法
    MySQL中concat函数
    mysql prepare语句使用
    修改表结构
  • 原文地址:https://www.cnblogs.com/yhm9/p/11360831.html
Copyright © 2020-2023  润新知