近日使用java访问zabbix api 在传递中文参数的时候,打死也出来结果。


通过postman等请求工具,发现传递的参数能返回结果。


那么就基本判断出是java 发送post请求时,未进行中文设置。


代码如下


public static String sendPost(String urlAddr,String param) {

    HttpURLConnection connection = null;
    DataOutputStream out = null;
    BufferedReader reader = null;
    StringBuffer sb = null;
    try {
        //创建连接
        java.net.URL url = new URL(urlAddr);
        connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setUseCaches(false);
        connection.setInstanceFollowRedirects(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Accept", "application/json-rpc"); // 设置接收数据的格式
        connection.setRequestProperty("Content-Type", "application/json-rpc; charset=UTF-8"); // 设置发送数据的格式
        //connection.setRequestProperty("Content-Type", "text/plain; charset=utf-8");

        connection.connect();

        //POST请求
        out = new DataOutputStream(connection.getOutputStream());
        System.out.print(param);
        JSONObject json = JSONObject.fromObject(param);
        out.write(param.getBytes("UTF-8"));
        out.flush();

        //读取响应
        reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String lines;
        sb = new StringBuffer("");
        while ((lines = reader.readLine()) != null) {
            lines = new String(lines.getBytes(), "utf-8");
            sb.append(lines);
        }

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        if (connection != null) {
            connection.disconnect();
        }
    }
    return sb.toString();
}


设置 connection.setRequestProperty("Content-Type", "application/json-rpc; charset=UTF-8")

没有效果


最后请教大神,各种设置。用一下语句,设置请求的参数。果然成功。

out.write(param.getBytes("UTF-8"));


Logo

北京人形旗下天工造物具身智能开源社区,聚焦具身天工与慧思开物两大平台

更多推荐