Twitter OAUTH Acces Token Response in JSON - json

I'm using Twitter's REST API to authorize an app. I just authorized the app with
https://api.twitter.com/oauth/authorize
and got an oauth_verifier from the redirect uri.
Then I just used
https://api.twitter.com/oauth/access_token
to get an access_token.
The problem is that the format of response I got from this method is text/plain. It's just like
oauth_token=783897656863051776-5hQfcJTv4FzFpPcyVRbnjPUbJXR29&oauth_token_secret=MViTPOOCaHNZrW6HTIFZ340bq1rutJKL8oqkBxRp2aiW&user_id=783897656863051776&screen_name=sWest&x_auth_expires=0
My query is that how to get the response in application/json format.
Any help will be appreciated !!!

You will need to parse it like application/x-www-form-urlencoded content, any language with HTTP Client libraries should provide this functionality. But it isn't clear what language and libraries you are using.
This example uses joauth library to parse
protected static Map<String, String> parseTokenMap(String tokenDetails) {
KeyValueHandler.SingleKeyValueHandler handler =
new KeyValueHandler.SingleKeyValueHandler();
KeyValueParser.StandardKeyValueParser bodyParser =
new KeyValueParser.StandardKeyValueParser("&", "=");
bodyParser.parse(tokenDetails, Collections.singletonList(handler));
return handler.toMap();
}

Related

Convert GET parameter to POST request body and extract specific JSON property

Background
I am making a spreadsheet that refers to information security license registration provided by the Japanese government (https://riss.ipa.go.jp/). The spreadsheet will be used on Microsoft Excel/LibreOffice Calc on Windows/Linux, so I want to avoid using platform-specific functionality like a script with the XMLHTTP60 module.
The site https://riss.ipa.go.jp has a URI that can retrieve registration information with a registration number (https://riss.ipa.go.jp/ajax/findRissRequest). The URI only works with a POST request with the application/x-www-form-urlencoded style request body and doesn't work with a GET request. The response of the URI is JSON format.
Problem #1
Microsoft Excel and LibreOffice Calc have the WEBSERVICE function that can be used to send a request to a URI. This function is supported on all platforms and is suitable for my use case.
Unfortunately, the WEBSERVICE function only supports GET requests, and the URI I want to use only supports POST requests.
Problem #2
Microsoft Excel and LibreOffice Calc have the FILTERXML function that can be used to extract a specific element from XML.
Unfortunately, the URI I want to use returns response in JSON format. There are no functions to parse JSON in Microsoft Excel and LibreOffice Calc.
Question
Is there any way to convert GET request to POST request and extract a JSON property?
For example, is there any Web API like http://api.example.com/convert/get-to-post?uri=https://riss.ipa.go.jp/ajax/findRissRequest&reg_no=000006&property=result.reg_date that calls https://riss.ipa.go.jp/ajax/findRissRequest with POST request body reg_no=000006 and extract property result.reg_date from its response?
After all, I could not find any existing services. So I made a web API service with AWS Lambda and API Gateway.
First, I made a Lambda function like this:
import json
import urllib.request
import urllib.parse
def lambda_handler(event, context):
queryStringParameters = event.get('params').get('querystring')
data = urllib.parse.urlencode(queryStringParameters)
data = data.encode('UTF-8')
f = urllib.request.urlopen("https://riss.ipa.go.jp/ajax/findRissRequest", data)
j = json.loads(f.read().decode('utf-8'))
return j
Then I made a resource with a GET method in API Gateway and connect it with the Lambda function.
In Integration Request, you have to use non-proxy integration. Also, you have to specify a mapping template for Content-Type application/json with Method Request passthrough template.
In Integration Response, you have to specify a mapping template for Content-Type application/xml like this:
<?xml version="1.0" encoding="UTF-8" ?>
#set($root = $input.path('$.result[0]'))
<result>
#foreach($key in $root.keySet())
<$key>$root.get($key)</$key>
#end
</result>
Then I added the HEAD and OPTIONS method for the resource. It is because the WEBSERVICE function of LibreOffice sends OPTIONS and HEAD requests before a GET request.
You can use a mock in Integration Request with a mapping template for Content-Type application/json like { "statusCode": 200 }.
The result of WEBSERVICE function will be #VALUE! without these methods.
Finally, I can get a property from a web service that only accepts POST requests and returns a JSON with WEBSERVICE and FILTERXML like:
=FILTERXML(WEBSERVICE("https://xxxxxxxxxx.execute-api.ap-northeast-1.amazonaws.com/prod/passthru?reg_no=000006"),"//result/reg_date")

Other technologies that can perform DTO request response like WCF

I have a WCF service that allows me make a request using an DTO and replies with a DTO for a WPF application. For example I pass a filter object for products which has a few properties for things I want to filter on and a couple of extras for paging, (the server will take care processing the filter object and getting the data) an example is like this.
public async Task<ObservableCollection<ProductListItem>> GetProductList(ProductFilter filter, int startIndex, int pageSize, string sortBy)
I am wondering if there exists any other technologies beside WCF that allow such an operation, From my preliminary research which may be quite off is that WebAPI uses the GET, POST, PUT verbs and routing rules which is quite different.
ServiceStack looks like it might be able to do this I can see on slide 37 at https://servicestack.net/features
it says.
List<Product> productOver2Bucks = client.Get(new FindProducts{PriceGreaterThan = 2})
Which seems pretty close but might still require Rest verbs as it uses a Get().
I don't know it it is FUD or not but I have been reading that soap over WCF is believed by some to be a legacy technology and JSON is the way of the future. So is there a replacement technology that will work with a method signature to the one I have above? That i could call from platforms such as Windows universal applications.
In ServiceStack if you design your Service with the Any method name, e.g
public object Any(Request request)
{
return new Response { ... };
}
This will allow calling this Service from Any HTTP Verb on any Format or endpoint (e.g. JSON, XML, MsgPack, Protocol Buffers, SOAP, Message Queue's, etc).
Also you don't need to define any [Route] for your Request DTO's since it will automatically fallback into using the pre-defined Routes when none are available.
public class Request : IReturn<Response> { ... }
public class Response { }
So with the above Service you can use ServiceStack .NET ServiceClients to call the API's using any verb, e.g:
var client = new JsonServiceClient(baseUrl);
Response response = client.Get(new Request { ... });
Response response = client.Post(new Request { ... });
When preferred you can also use the async API's, e.g:
var response = await client.GetAsync(new Request { ... });
var response = await client.PostAsync(new Request { ... });
Which if you don't care for using verbs you can use the generic Send API, e.g:
Response response = client.Send(new Request { ... });
Which just uses POST underneath, although it's highly recommended to use Get for "read only" queries as it will allow the Services HTTP responses to be cached by any intermediate HTTP Middleware or proxies.
Add ServiceStack Reference
Also if you're coming from WCF you'll also enjoy ServiceStack's, Add ServiceStack Reference which provides a number of advantages over WCF's Add Service Reference feature but still provides the same utility in being able to generate a typed API from a remote url for:
C# Add Reference
F# Add Reference
VB.NET Add Reference
TypeScript Add Reference
With more languages to follow.
Advantages over SOAP
Whilst ServiceStack still enables WSDL's, XSD's for your Services so they can be called from SOAP 1.1/1.2 endpoints for legacy compatible reasons - there are a number of reasons why using clean HTTP and JSON/XML API's are preferred.

RestSharp usage for sending and receiving data

I have successfully created my app and now want to connect it to a localhost to check the working of my app. I have been suggested to use restsharp for connecting to the server using php and json to receive data from server.
I have looked at codes for both but do not completely understand how the process works. I have looked into all forums but found could snippets with no explanation as how it works. I have even tried restsharp.org and google search results. Please explain me as to how this works.
RestSharp is a library that helps you invoking REST web services.
You use RestSharp on your client to invoke Rest style Web Services (send and receive data)
Here is an example on the usage of your service:
var client = new RestClient(baseUrl);
var request = new RestRequest("/*rest_resource*/", Method.POST);
// see Rest services
// set the request format - HTTP Content-Type text/xml
request.RequestFormat = DataFormat.Xml;
// add data to the request
request.AddBody("<books><book>RestSharp Book</book></books>");
/* send the request and if your service returns text put the as expected return type; otherwise you will get raw byte array*/
IRestResponse response = client.Execute(request);
//HTTP status code 200-success
Assert.IsTrue(response.StatusCode == HttpStatusCode.OK);
Assert.IsTrue(!string.IsNullOrEmpty(response.Data)); // the response is not empty

Can we have JSON object as input parameter to http get for RESTful web services?

I am new to RESTful web services. Can i have a method like below which accepts JSON as object ?
#GET
#Produces("application/json")
#Consumes("application/json")
#Path("/test")
public Response modifyJson(JSONObject input);
I believe that by default it is not possible to send Json as input to a GET, only other verbs (POST, PUT...)
Having said that, technically it depends of the service to allow you or not to send input on GET. The usual is to send query string parameters with GET.
Hope it helps
Ademar

GWT RequestBuilder POST JSON application/json

I'm trying to send JSON data to a server.
RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, url);
builder.setHeader("Content-Type", "application/json");
builder.setRequestData(getJSONString());
builder.setCallback(myCallbackObject);
builder.send();
I do this in eclipse and I saw in the TCP/IP Monitor that my JSON Data is not transmitted as post in the request. If I ask for
builder.getRequestData();
I can see the JSON data is right there.
What do I need for the data to get on the server?
You might be running into the browser's same-origin policy if the url that you are attempting to connect to is not from the same origin as your GWT nocache.js file. Is your callback's onFailure() being called? Also, see if Request.getSatusCode() returns 0, which is indicative of SOP problems.
To simply post JSON data with HTTP post, you can use GWT Overlay Types to define a post method using JQuery. A possible snapshot:
public static native void post(String json) /*-{
var data = JSON.parse(json);
$wnd.$.post(url, data);
}-*/;
I don't know if it is necessary to add JQuery to your HTML. I did, and worked. You can do this by adding the following line to your .html file:
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Then, you can simply call that method in your java code:
post(json);
(: