简体   繁体   English

How to parse JSON response from an API url using https request in java?

[英]How to parse JSON response from an API url using https request in java?

how to parse the JSON response from an api url using java?如何使用 Z93F725A07423FE1C8F46ZD4 解析来自 api url 的 JSON 响应? When I run the below code I am getting SocketTimeoutException.当我运行下面的代码时,我得到了 SocketTimeoutException。 but when browse the URL in the Chrome and Microsoft Edge i am getting the JSON data.但是当在 Chrome 和 Microsoft Edge 中浏览 URL 时,我得到了 JSON 数据。

url:"https://www.nseindia.com/api/quote-derivative?symbol=RELIANCE" (use only for testing purpose. not for commercial use) url:“https://www.nseindia.com/api/quote-derivative?symbol=RELIANCE”(仅用于测试目的。不可用于商业用途)

Java Code: Java 代码:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.JSONObject;



public class HTTP_Request {

    public static void main(String[] args) {
        try {
        Send_HTTP_Request.call_me();
    } catch (Exception e) {
        e.printStackTrace();
    }
    }
    
    public static void call_me() throws Exception {
    
        String url ="https://www.nseindia.com/api/quote-derivative?symbol=RELIANCE";
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        // optional default is GET
        con.setRequestMethod("GET");
        //add request header
        con.setRequestProperty("User-Agent", "Mozilla/5.0");
        int responseCode = con.getResponseCode();
        System.out.println("\nSending 'GET' request to URL : " + url);
        System.out.println("Response Code : " + responseCode);
        BufferedReader in = new BufferedReader(
                new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
        
        //print in String
        System.out.println(response.toString());
        
        //Read JSON response and print
       // JSONObject myResponse = new JSONObject(response.toString());
       // System.out.println("result after Reading JSON Response");
       // System.out.println("origin- "+myResponse.getString("origin"));
         
        }
}

look what happens when you call the provided url from a shell curl:看看当您从 shell curl 调用提供的 url 时会发生什么:

> $ curl 'https://www.nseindia.com/api/quote-derivative?symbol=RELIANCE'                                                 [±master ●●▴]
<HTML><HEAD>
<TITLE>Access Denied</TITLE>
</HEAD><BODY>
<H1>Access Denied</H1>

You don't have permission to access "http&#58;&#47;&#47;www&#46;nseindia&#46;com&#47;api&#47;quote&#45;derivative&#63;" on this server.<P>
Reference&#32;&#35;18&#46;15b5655f&#46;1595338785&#46;264b3809
</BODY>
</HTML>

So, I guess nseindia is blocking the request because is not coming from a browser.所以,我猜 nseindia 阻止了请求,因为它不是来自浏览器。 But, if you try this:但是,如果你试试这个:

curl 'https://www.nseindia.com/api/quote-derivative?symbol=RELIANCE' -H 'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:78.0) Gecko/20100101 Firefox/78.0' -H 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8' -H 'Accept-Language: en-US,en;q=0.5' --compressed -H 'Connection: keep-alive' -H 'Cookie: ak_bmsc=D709927FAB6A44F1C243E20E9199ABA35F65B5158B040000E1EF165F44B95756~plIifDJa9J1EHznQiR/zQpjmGEFWOE88N83Yuqa0oOcgvvYh7eLlgD5MSFVhCZZOObVMZ7UDwEzmOQ2V2lJ6W9pPf6zEbQT1Je27i6h3hrAIyBYFMplV1EDo7rSLxXmCk+HGL3ynHmuPJsePDPD7WTljjTMnM1qpvixsCMEtM1BlmVmuXQijd8cKjWxLeLaf/cNAEJB6VC7SXOq+j6uj6oi9xF/Z2NYB905XnUg9YppXM=' -H 'Upgrade-Insecure-Requests: 1' -H 'Pragma: no-cache' -H 'Cache-Control: no-cache'

you get a json in the response.你在响应中得到一个 json 。

{"info":{"symbol":"RELIANCE","companyName":"Reliance Industries Limited",.......}

So you need to add a couple of HTTP Headers to your request, something like:因此,您需要在请求中添加几个 HTTP 标头,例如:

con.setRequestProperty("User-Agent", "Mozilla/5.0");
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
con.setRequestProperty("Accept", "text/html");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM