如何将重音字符传递给 REST API(Github 问题)



我正在尝试使用 Github API 向特定存储库开放问题。我面临的问题是,当我使用重音字符(例如:á,é,í,ó,ú)时,请求失败并出现以下异常。

java.io.FileNotFoundException: https://api.github.com/repos/myorganization/myrepo/issues

我尝试过:

String title = "MyTitle";
String description = "áé"
JSONObject jsonBody = new JSONObject();
jsonBody.put("title", title);
jsonBody.put("body", description);
JSONObject urlParameters = jsonBody;
int timeout = 5000;
URL url;
HttpURLConnection connection = null;
    try {
        // Create connection
        url = new URL(MyConstants.GITHUB_REPO);
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type","application/json");
        connection.setRequestProperty("Authorization", MyConstants.GITHUB_TOKEN);
        connection.setUseCaches(false);
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setConnectTimeout(timeout);
        connection.setReadTimeout(timeout);
        // Send request
        DataOutputStream wr = new DataOutputStream(
                connection.getOutputStream());
        wr.writeBytes(urlParameters.toString());
        wr.flush();
        wr.close();
        // Get Response
        InputStream is = connection.getInputStream();
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        String line;
        StringBuffer response = new StringBuffer();
        while ((line = rd.readLine()) != null) {
            response.append(line);
            response.append('r');
        }
        rd.close();
        is.close();
        return response.toString();
    } catch (Exception e) {
        e.printStackTrace();
    }

我想知道管理发送到 API 的重音字符的正确方法是什么。

问题已经有了答案 使用 HttpURL 发送 UTF-8 字符串

在您的情况下,您可以简单地对 JSON 字符串进行编码。

byte[] buffer = Charset.forName("UTF-8").encode(urlParameters.toString()).array();
wr.write(buffer,0,buffer.length);

相关内容

  • 没有找到相关文章

最新更新