我用 Java 编写了一个 http post 请求来访问 Bigquery 数据。以下是我的代码:
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
public class Post {
static String url =
"https://www.googleapis.com/bigquery/v2/projects/<project-ID>/queries?key=<API Broweser key>";
public static void main(String[] args) throws Exception {
//Instantiate an HttpClient
HttpClient client = new HttpClient();
//Instantiate a GET HTTP method
PostMethod method = new PostMethod(url);
method.setRequestHeader("Content-type",
"application/json");
method.setRequestHeader("Authorization",
URLEncoder.encode("Bearer <authorization-token>","UTF-8"));
//Define name-value pairs to set into the QueryString
NameValuePair nvp1= new NameValuePair("query","select * from <TableName> limit 10");
method.setQueryString(new NameValuePair[]{nvp1});
try{
int statusCode = client.executeMethod(method);
System.out.println("Status Code = "+statusCode);
System.out.println("QueryString>>> "+method.getQueryString());
System.out.println("Status Text>>>"
+HttpStatus.getStatusText(statusCode));
//Get data as a String
System.out.println(method.getResponseBodyAsString());
//OR as a byte array
byte [] res = method.getResponseBody();
//write to file
FileOutputStream fos= new FileOutputStream("donepage.html");
fos.write(res);
//release connection
method.releaseConnection();
}
catch(IOException e) {
e.printStackTrace();
}
}
}
我收到以下错误:
Unauthorized
{
"error": {
"errors": [
{
"domain": "global",
"reason": "authError",
"message": "Invalid Credentials",
"locationType": "header",
"location": "Authorization"
}
],
"code": 401,
"message": "Invalid Credentials"
}
}
请注意,我可以使用相同的授权令牌通过 BigQuery 命令行工具访问数据。我使用以下内容生成了授权令牌:
https://accounts.google.com/o/oauth2/auth?
scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile&
redirect_uri=urn:ietf:wg:oauth:2.0:oob&
response_type=code&
client_id=812741506391-h38jh0j4fv0ce1krdkiq0hfvt6n5amrf.apps.googleusercontent.com
这遵循以下说明:https ://developers.google.com/bigquery/authorization