开发者

How do I pass this param properly?

开发者 https://www.devze.com 2023-04-05 06:13 出处:网络
I want to make an API request with a tex开发者_Python百科t param, with information I currently have in params[:brand][:tag_list] which seems to be saved as a single comma-delimited string. What\'s the

I want to make an API request with a tex开发者_Python百科t param, with information I currently have in params[:brand][:tag_list] which seems to be saved as a single comma-delimited string. What's the correct way to make the API request?

Controller code:

current_user.tag(@brand, :with => params[:brand][:tag_list], :on => :tags)

url = "http://www.viralheat.com/api/sentiment/review.json"
@sentiment_response = url.to_uri.get(
  :api_key => 'MY_KEY',
  :text => :tag_list ).deserialize #This is what I'm currently using and is wrong

Response codes from log:

<- (GET 49996946161 2204098100) http://www.viralheat.com:80/api/sentiment/review.json?api_key=MY_KEY&text=tag_list
-> (GET 49996946161 2204098100) 200 OK (62 bytes 3.09s)


Looking up the docs for viralheat, it looks like their api accepts exactly two parameters: api_key, and text. Assuming params[:brand][:tag_list] a comma-delimited string, you can form your request like so:

current_user.tag(@brand, :with => params[:brand][:tag_list], :on => :tags)

url = "http://www.viralheat.com/api/sentiment/review.json"
@sentiment_response = url.to_uri.get(
  :api_key => 'MY_KEY',
  :text => params[:brand][:tag_list].split(',').join('&') ).deserialize

This should create the url:

http://www.viralheat.com/api/sentiment/review.json?api_key=MY_KEY&text=cat%26dog%26​mouse

params[:brand][:tag_list].split(',') breaks your string into an array, and join('&') turns it back into a string, but this time delimited by ampersands (which seems to be what you want, based on what you said in a comment on your original post). Your uri.get method should escape the ampersands in the uri, which is why you see the %26s in the final url. This is correct.

0

精彩评论

暂无评论...
验证码 换一张
取 消