Skip to content

Instantly share code, notes, and snippets.

@ydn
Created March 5, 2015 20:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ydn/9a58ebe6e8fb90203d46 to your computer and use it in GitHub Desktop.
Save ydn/9a58ebe6e8fb90203d46 to your computer and use it in GitHub Desktop.
BOSS PlaceFinder API
var request = require('request');
var qs = require('querystring');
var url = 'https://yboss.yahooapis.com/geo/placefinder';
var params = qs.stringify({
q: '701 First Ave, Sunnyvale, CA',
flags: 'J'
});
var oauth = {
consumer_key: 'Your Consumer Key',
consumer_secret: 'Your Consumer Secret'
};
request.get({ url: url + '?' + params, oauth: oauth, json: true }, function(e, r, body) {
console.log(body);
});
using System;
using System.Net;
using OAuth;
namespace ConsoleApplication1{
class Program{
static void Main(string[] args){
string consumerKey = "...";
string consumerSecret = "...";
var uri = new Uri("https://yboss.yahooapis.com/geo/placefinder?callback=json2&q=701+first+avenue+sunnnyvale");
string url, param;
var oAuth = new OAuthBase();
var nonce = oAuth.GenerateNonce();
var timeStamp = oAuth.GenerateTimeStamp();
var signature = oAuth.GenerateSignature(uri, consumerKey,
consumerSecret, string.Empty, string.Empty, "GET", timeStamp, nonce,
OAuthBase.SignatureTypes.HMACSHA1, out url, out param);
using (WebRequest.Create(string.Format("{0}?{1}&oauth_signature={2}",
url, param, signature)).GetResponse()) { }
}}}
/** SignPostTest.java **/
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;
import oauth.signpost.OAuthConsumer;
import oauth.signpost.basic.DefaultOAuthConsumer;
/**
* Sample code to use Yahoo! Search BOSS
*
* Please include the following libraries
* 1. Apache Log4j
* 2. oAuth Signpost
*
* @author xyz
*/
public class SignPostTest {
private static final Logger log = Logger.getLogger(SignPostTest.class);
protected static String yahooServer = "https://yboss.yahooapis.com/geo/";
// Please provide your consumer key here
private static String consumer_key = "";
// Please provide your consumer secret here
private static String consumer_secret = "";
/** The HTTPS request object used for the connection */
private static StHttpRequest httpsRequest = new StHttpRequest();
/** Encode Format */
private static final String ENCODE_FORMAT = "UTF-8";
/** Call Type */
private static final String callType = "placefinder";
private static final int HTTP_STATUS_OK = 200;
/**
*
* @return
*/
public int returnHttpData()
throws UnsupportedEncodingException,
Exception{
if(this.isConsumerKeyExists() && this.isConsumerSecretExists()) {
// Start with call Type
String params = callType;
// Add query
params = params.concat("?q=");
// Encode Query string before concatenating
params = params.concat(URLEncoder.encode(this.getSearchString(), "UTF-8"));
// Create final URL
String url = yahooServer + params;
// Create oAuth Consumer
OAuthConsumer consumer = new DefaultOAuthConsumer(consumer_key, consumer_secret);
// Set the HTTPS request correctly
httpsRequest.setOAuthConsumer(consumer);
try {
log.info("sending get request to" + URLDecoder.decode(url, ENCODE_FORMAT));
int responseCode = httpsRequest.sendGetRequest(url);
// Send the request
if(responseCode == HTTP_STATUS_OK) {
log.info("Response ");
} else {
log.error("Error in response due to status code = " + responseCode);
}
log.info(httpsRequest.getResponseBody());
} catch(UnsupportedEncodingException e) {
log.error("Encoding/Decording error");
} catch (IOException e) {
log.error("Error with HTTP IO", e);
} catch (Exception e) {
log.error(httpsRequest.getResponseBody(), e);
return 0;
}
} else {
log.error("Key/Secret does not exist");
}
return 1;
}
private String getSearchString() {
return "701+first+avenue+sunnyvale";
}
private boolean isConsumerKeyExists() {
if(consumer_key.isEmpty()) {
log.error("Consumer Key is missing. Please provide the key");
return false;
}
return true;
}
private boolean isConsumerSecretExists() {
if(consumer_secret.isEmpty()) {
log.error("Consumer Secret is missing. Please provide the key");
return false;
}
return true;
}
/**
* @param args
*/
public static void main(String[] args) {
BasicConfigurator.configure();
try {
SignPostTest signPostTest = new SignPostTest();
signPostTest.returnHttpData();
} catch (Exception e) {
log.info("Error", e);
}
}
}
/** StHttpRequest **/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpsURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import org.apache.log4j.Logger;
import oauth.signpost.OAuthConsumer;
import oauth.signpost.exception.OAuthCommunicationException;
import oauth.signpost.exception.OAuthExpectationFailedException;
import oauth.signpost.exception.OAuthMessageSignerException;
/**
* @author David Hardtke
* @author xyz
* Simple HTTPS Request implementation
*/
public class StHttpRequest {
private static final Logger log = Logger.getLogger(StHttpRequest.class);
private String responseBody = "";
private OAuthConsumer consumer = null;
/** Default Constructor */
public StHttpRequest() { }
public StHttpRequest(OAuthConsumer consumer) {
this.consumer = consumer;
}
public HttpsURLConnection getConnection(String url)
throws IOException,
OAuthMessageSignerException,
OAuthExpectationFailedException,
OAuthCommunicationException
{
try {
URL u = new URL(url);
HttpsURLConnection uc = (HttpsURLConnection) u.openConnection();
if (consumer != null) {
try {
log.info("Signing the oAuth consumer");
consumer.sign(uc);
} catch (OAuthMessageSignerException e) {
log.error("Error signing the consumer", e);
throw e;
} catch (OAuthExpectationFailedException e) {
log.error("Error signing the consumer", e);
throw e;
} catch (OAuthCommunicationException e) {
log.error("Error signing the consumer", e);
throw e;
}
uc.connect();
}
return uc;
} catch (IOException e) {
log.error("Error signing the consumer", e);
throw e;
}
}
/**
* Sends an HTTP GET request to a url
*
* @param url the url
* @return - HTTP response code
*/
public int sendGetRequest(String url)
throws IOException,
OAuthMessageSignerException,
OAuthExpectationFailedException,
OAuthCommunicationException {
int responseCode = 500;
try {
HttpsURLConnection uc = getConnection(url);
responseCode = uc.getResponseCode();
if(200 == responseCode || 401 == responseCode || 404 == responseCode){
BufferedReader rd = new BufferedReader(new InputStreamReader(responseCode==200?uc.getInputStream():uc.getErrorStream()));
StringBuffer sb = new StringBuffer();
String line;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
rd.close();
setResponseBody(sb.toString());
}
} catch (MalformedURLException ex) {
throw new IOException( url + " is not valid");
} catch (IOException ie) {
throw new IOException("IO Exception " + ie.getMessage());
}
return responseCode;
}
/**
* Return the Response body
* @return String
*/
public String getResponseBody() {
return responseBody;
}
/**
* Setter
* @param responseBody
*/
public void setResponseBody(String responseBody) {
if (null != responseBody) {
this.responseBody = responseBody;
}
}
/**
* Set the oAuth consumer
* @param consumer
*/
public void setOAuthConsumer(OAuthConsumer consumer) {
this.consumer = consumer;
}
}
<?php
/* Pre-requisite: Download the required PHP OAuth class from http://oauth.googlecode.com/svn/code/php/OAuth.php. This is used below */
require("OAuth.php");
$url = "https://yboss.yahooapis.com/geo/placefinder";
$cc_key = "ENTER YOUR CONSUMER KEY HERE";
$cc_secret = "ENTER YOUR CONSUMER SECRET HERE";
$args = array();
$args["q"] = "701+first+avenue+sunnnyvale";
$consumer = new OAuthConsumer($cc_key, $cc_secret);
$request = OAuthRequest::from_consumer_and_token($consumer, NULL,"GET", $url,
$args);
$request->sign_request(new OAuthSignatureMethod_HMAC_SHA1(), $consumer, NULL);
$url = sprintf("%s?%s", $url, OAuthUtil::build_http_query($args));
$ch = curl_init();
$headers = array($request->to_header());
curl_setopt($ch,CURLOPT_ENCODING , "gzip");
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
print_r("Request Headers\n");
print_r($headers);
$rsp = curl_exec($ch);
print_r("\nHere is the XML response for Placefinder\n");
print_r($rsp);
?>
use strict;
use lib 'extra_mods';
use lib 'extra_mods/5.8';
use JSON;
use Net::OAuth;
use LWP::UserAgent;
use Data::Dumper;
$Net::OAuth::PROTOCOL_VERSION = Net::OAuth::PROTOCOL_VERSION_1_0A;
my $expected_result_format = 'xml'; #xml or json
my %args;
$args{q} = "701+first+avenue+sunnnyvale"; # This is the query we are searching for
$args{format} = $expected_result_format;
$args{count} = 1; # number of results to be returned
my $buckets = "placefinder"; # placefinder, placespotter(BOSS Geo services)
print get_response(\%args,$buckets);
sub get_response {
my %args = %{(shift)};
my $buckets = shift;
my $ua = LWP::UserAgent->new;
# PROVIDE YOUR KEY HERE
my $cc_key = "";
# PROVIDE YOUR SECRET HERE
my $cc_secret = "";
# Source Url
my $url = "https://yboss.yahooapis.com/geo/$buckets";
# Create request
my $request = Net::OAuth->request("request token")->new(
consumer_key => $cc_key,
consumer_secret => $cc_secret,
request_url => $url,
request_method => 'GET',
signature_method => 'HMAC-SHA1',
timestamp => time,
nonce => 'hsu94j3884jdopsl',
callback => 'http://printer.example.com/request_token_ready',
extra_params => \%args
);
# Sign request
$request->sign;
# Get message to the Service Provider
my $res = $ua->get($request->to_url);
# If request is success, display content
if ($res->is_success) {
return $res->content;
}
else {
# Print error and die
Dumper $res;
die "Something went wrong";
}
}
require 'oauth_util.rb'
require 'net/http'
def get_response(args,buckets)
url = "https://yboss.yahooapis.com/geo/"+buckets+"?"
arg_count = 0
args.each do|key,value|
url = url + key + "=" + value+"&"
++arg_count
end
if(arg_count > 0)
url.slice!(url.length-1)
end
parsed_url = URI.parse( url )
o = OauthUtil.new
o.consumer_key = "<em><strong>ADD YOUR KEY HERE</strong></em>"
o.consumer_secret = "<strong>ADD YOUR SECRET HERE</strong>"
Net::HTTP.start( parsed_url.host ) { | http |
req = Net::HTTP::Get.new "#{ parsed_url.path }?#{ o.sign(parsed_url).query_string }"
response = http.request(req)
return response.read_body
}
end
args = Hash.new
args["format"] = "xml"
#args["format"] = "json"
args["q"] = "watch1"
args["count"] = "1"
buckets = "placefinder"
print get_response(args,buckets)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment