jeudi 16 juin 2016

Unable to get JSON response from URLConnection

I am trying to read a response from googleapi using java URLConnection.

In browser if i query "https://www.googleapis.com/pagespeedonline/v2/runPagespeed?url=https%3A%2F%2Fwww.zauq.se&strategy=mobilez"

i gets response in JSON formate.

{
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "invalidParameter",
    "message": "Invalid string value: 'mobilez'. Allowed values: [desktop, mobile]",
    "locationType": "parameter",
    "location": "strategy"
   }
  ],
  "code": 400,
  "message": "Invalid string value: 'mobilez'. Allowed values: [desktop, mobile]"
 }
}

But when i use following code.

URL url = null;
            System.setProperty("http.agent", "");

            url = new URL("https://www.googleapis.com/pagespeedonline/v2/runPagespeed?url=https%3A%2F%2Fwww.zauq.se&strategy=mobilez");//"https://www.googleapis.com/pagespeedonline/v2/runPagespeed?url=" + paramUrl + "&strategy=" + paramStrategy);
            URLConnection conn = url.openConnection();
            conn.setRequestProperty("Accept", "application/json");
            conn.setRequestProperty("User-Agent", "Mozilla/5.0");
            BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String strTemp = "";
            StringBuilder sb = new StringBuilder();

            while ((null != (strTemp = br.readLine())))
            {
                sb.append(strTemp);
                if (dump)
                {
                    System.out.println(strTemp);
                }
            }

i get IO Exception

java.io.IOException: Server returned HTTP response code: 400 for URL: https://www.googleapis.com/pagespeedonline/v2/runPagespeed?url=https%3A%2F%2Fwww.zauq.se&strategy=mobilez
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1627)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:254)
    at amirTest.PageSpeedCheck.main(PageSpeedCheck.java:62)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)

/ but i need to get JSON response.

Please suggest me the change need to make to get the JSON as a response.

Aucun commentaire:

Enregistrer un commentaire