尝试通过HttpURLConnection

时间:2019-10-03 03:33:42

标签: java rest api

尝试使用默认的httpconnection来访问URL,并获得套接字异常。 我曾尝试通过邮递员手动关闭URL并关闭SSL认证,但效果很好,我也尝试了未经过SSL认证检查的URL,但似乎无济于事。帮助菜鸟。

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class GetCall_TEst1 {

    // http://localhost:8080/RESTfulExample/json/product/get
    public static void main(String[] args) {

        try {

            URL url = new URL("https://**MyURL*******");

            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            // adding request header
            conn.setRequestProperty("Referer", "https://**RedactedSomeValue***");

            if (conn.getResponseCode() != 200) {
                throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
            }

            BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));

            String output;
            System.out.println("Output from Server .... \n");
            while ((output = br.readLine()) != null) {
                System.out.println(output);
            }

            conn.disconnect();

        } catch (MalformedURLException e) {

            e.printStackTrace();

        } catch (IOException e) {

            e.printStackTrace();

        }

    }

}

0 个答案:

没有答案