javahttppostman

Getting 301 while doing HTTP get call using Java but getting 200 while doing same using Postman


I am using Java for doing a GET request on a given URL. I am getting 301 error. But when I do the same GET req using postman, I am getting 200. I am not able to figure out what is wrong. Here is my Java code-

public static void main(String args[]) throws IOException {
    URL url = new URL("http://cdn-api.co-vin.in/api/v2/appointment/sessions/public/findByDistrict/?district_id=637&date=22-05-2021");
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    con.setRequestMethod("GET");
    con.setRequestProperty("User-Agent", "PostmanRuntime/7.26.10");
    con.setRequestProperty("Accept-Language", "en_US");
    con.setRequestProperty("Content-Type", "application/json");
    con.setRequestProperty("Accept", "application/json");
    BufferedReader in = new BufferedReader(new InputStreamReader( con.getInputStream()));
    String inputLine;
    while ((inputLine = in.readLine()) != null) {
        System.out.println(inputLine);
    }
    in.close();
}

Let me know if this can be resolved.


Solution

  • If you are getting 301 Moved HTTP status code, there is a redirection happening at the server, and, the HttpURLConnection is supposed to follow redirects only if they use the same protocol. Hence, you should try changing the URL protocol from http:// to https://