协议获取Java URL

时间:2014-03-20 16:03:01

标签: java url google-api protocols

我试图获取查询谷歌时找到的所有网站的JSON格式。

代码:

import java.io.FileWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;

/**
 * Created by Vlad on 19/03/14.
 */
public class Query {   
    public static void main(String[] args){
        try{
        String arg;
            arg = "random";

        URL url = new URL("GET https://www.googleapis.com/customsearch/v1?key=&cx=017576662512468239146:omuauf_lfve&q=" + arg);
        InputStreamReader reader = new InputStreamReader(url.openStream(),"UTF-8");

    int ch;
            while((ch = reader.read()) != -1){
    System.out.print(ch);
            }

        }catch(Exception e)
        {
            System.out.println("This ain't good");
            System.out.println(e);
        }
    }    
}

例外:

  

java.net.MalformedURLException:无协议:GET https://www.googleapis.com/customsearch/v1?key=AIzaSyCS26VtzuCs7bEpC821X_l0io_PHc4-8tY&cx=017576662512468239146:omuauf_lfve&q=random

2 个答案:

答案 0 :(得分:2)

您应该删除开头的GET;)

您应该通过以下方式替换您的代码:

URL url = new URL("https://www.googleapis.com/customsearch/v1?key=AIzaSyCS26VtzuCs7bEpC821X_l0io_PHc4-8tY&cx=017576662512468239146:omuauf_lfve&q=" + arg);

网址永远不会以GETPOST或其他类似内容开始;)

答案 1 :(得分:1)

网址应该以转让协议开始,GET https://www.googleapis.com/customsearch/v1?key=AIzaSyCS26VtzuCs7bEpC821X_l0io_PHc4-8tY&cx=017576662512468239146:omuauf_lfve&q=randomGET开头,这就是收到异常的原因。

将其更改为https://www.googleapis.com/customsearch/v1?key=AIzaSyCS26VtzuCs7bEpC821X_l0io_PHc4-8tY&cx=017576662512468239146:omuauf_lfve&q=random