HTTP request header doesn't work

I've been trying to "download" json into a string but there problem is that the API I'm using ( needs to get the request header Accept set to application/json otherwise it returns HTML and not json. I tried setting setRequestProperty and when I debug it it looks the header is actually set but for some reason it still returns HTML. This is not website's fault because I tried using API with Postman and it worked fine. Here's my code:

    private static String readUrl(String urlString) throws Exception {
    BufferedReader reader = null;
    try {
        URL url = new URL(urlString);
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestProperty("Accept", "application/json");
        reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
        StringBuffer buffer = new StringBuffer();
        int read;
        char[] chars = new char[1024];
        while ((read = != -1)
            buffer.append(chars, 0, read);

        return buffer.toString();
    } finally {
        if (reader != null)

I hope I've been specific enough

2 answers

  • answered 2018-04-14 15:09 parlad neupane

    May be object mutation, i pass doing this way,

    public String getJSON(String url, int timeout) {
    HttpURLConnection c = null;
    try {
        URL u = new URL(url);
        c = (HttpURLConnection) u.openConnection();
        c.setRequestProperty("Content-length", "0");
        int status = c.getResponseCode();
        switch (status) {
            case 200:
            case 201:
                BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = br.readLine()) != null) {
                return sb.toString();
    } catch (MalformedURLException ex) {
        Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
    } finally {
       if (c != null) {
          try {
          } catch (Exception ex) {
             Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
    return null;

    This is a function , more genralize , pass your url in first parameter of function and for the second , pass number of millisecond you want to hit that url.

  • answered 2018-04-14 15:55 Ampati Hareesh

    Postman :The Postman is using the redirect internally, turn on interceptor and turnoff the redirect under general tab in settings

    YourCode: change the url to secured one,use protocol https

    Hope this helps :)