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

时间:2017-02-01 14:57:35

标签: java json httpurlconnection

我正在尝试使用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的重音字符的正确方法是什么。

1 个答案:

答案 0 :(得分:2)

问题的答案已经Sending UTF-8 string using HttpURLConnection

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

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