0

I'm attempting to use Github API to open issues to specific repositories. The problem I'm facing is that when I use accented characters (example: á,é,í,ó,ú), the request fails with the following exception.

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

What I've tried:

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();
    }

I would like to know what is the proper way to manage accented characters sent to the API.

JanPl
  • 794
  • 6
  • 19
Cristian
  • 199
  • 2
  • 13

1 Answers1

2

Question has an answer already Sending UTF-8 string using HttpURLConnection

In your case you can simply encode the JSON string.

byte[] buffer = Charset.forName("UTF-8").encode(urlParameters.toString()).array();
wr.write(buffer,0,buffer.length);
Community
  • 1
  • 1
JanPl
  • 794
  • 6
  • 19