I am trying to run a sample WebRequest to return JSON data. I keep on getting XML response. any idea why?
this.btnGetCoordinates.TouchUpInside += (sender, e) => {
var rxcui = "198440";
var request = HttpWebRequest.Create(string.Format (#"http://rxnav.nlm.nih.gov/REST/RxTerms/rxcui/{0}/allinfo", rxcui));
request.Method = "GET";
request.ContentType = "application/json";
request.BeginGetResponse(new AsyncCallback(ProcessGetCoordinates), request);
};
return true;
}
void ProcessGetCoordinates(IAsyncResult iar) {
HttpWebRequest request = (HttpWebRequest)iar.AsyncState;
using (HttpWebResponse response = (HttpWebResponse)request.EndGetResponse (iar)) {
if (response.StatusCode != HttpStatusCode.OK) {
Console.Out.WriteLine("Error fetching data. Server returned status code: {0}", response.StatusCode);
}
using (StreamReader strm = new StreamReader (response.GetResponseStream())) {
string content = strm.ReadToEnd ();
if (string.IsNullOrWhiteSpace (content)) {
Console.Out.WriteLine("Response contained empty body...");
} else {
Console.Out.WriteLine("Response Body: \r\n {0}", content);
}
}
}
}
You need to set the Accept header on your request to "application/json".
var request = HttpWebRequest.Create(string.Format (#"http://rxnav.nlm.nih.gov/REST/RxTerms/rxcui/{0}/allinfo", rxcui));
request.Method = "GET";
request.Accept = "application/json";
Related
I have the following headers:
X-NewRelic-ID: VQACUF9bCBABU1JQAAQPU1I=
X-Device-Descriptor-Id: YWY1Zjk5OGI5N2U1ODg0Zg
User-Agent: Sahibinden-Android/4.5.2 (671; Android 5.1.1; Android Android SDK built for x86)
x-api-key: e91092ad5ea2e030c201ce9ac4373f6b565a7842
x-client-profile: Generic_v2.1
x-device-id: d4dc022224a74bc7964cb4d449cd32c2
x-timestamp: 1591117620862
x-api-hash: DF7AB8944EDB3140BCB2A3EA9BC95F70C3200DB7
adid: b165e39f-b0ee-4b22-aee5-df3675136c2c
Content-Type: application/json; charset=utf-8
X-J3PopQvX-e: a;grA22x5m7f3tr-0iQLVuq4BLsOW3uMVgYrreUpRM5M9sSufn0I0K5QO-LrGIm1gY8IHM_GtH_7uQ-cRTU-eV9762ivhZAO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p-CyeWKRkGOZ_gafCibxwnJ9mslopc0WviVvbbwBKrNuZrZlWXQrnzi8ml=oq35l4xWs0Nb7VZOYezEiUgoayg7pFm8eLV02GiU7lrpQMqF_pl04dXo3QAEwDW_YgIrLCtBoVM92dckSfScDL12nZREI3Yd-V3dkN23vFr2cFXbBKoHK2uVDTqUyzMxDgqHkXxPu3rzp9g0FSA95TgKke0ikBsX7KrdNBc9cQNgj2AouCXwIzzAExo2pa2wqJk7zXna3ObWHbgk1dpiJ=dk_Gbr3LOJ-CeTWGANr=u1Cnyo-weSvvLGMlQTJjWOedNDCtduC193Bfeqn2brGiKSUV3rx09ywipxjJVjGW=eJ_k0Cex7bIq_RNZJHso1qzQ-R=IR59XtaSyM9BLwKNJ4tOiCpMltCJyWOd0yJnYcgZSUCiLBINMh-e7F_Si-e_1c3VH5UqyENO8YvR59-IYl4qUQs5NpIEZc5Hl0lImENjL_7WsBB7jue4Ty0JPxXrYo3ME_P0Xc0UIEJKN3CQCzKl9a5ZmmMTrHyJHNNW0FSrMsAgUXRtDH_MuExGdqcEjgr-8hhoS2kAV_JER1FupukcsGi0JLegpLEYF9GLDnUoDCDrPRP5tQb21gQUpEdvozNmXdVNRCukPDJeRSSYr4iCM5=-3UzYPSDwkb=_7Ea=WvgXvKtIeKbYcF5ZPk8OU-rq_ysU2Slfaf7fgHHR4Aif2cx_ZTekL=0W5LQL3AZv2QBh-VjjNri
X-J3PopQvX-b: -1o1lvb
X-J3PopQvX-c: AEC_kwhyAQAA125LdUCpBmDn_gaT36bu5R1v7tLmaWD2Y_AhYfLAeVsrDVYa
X-J3PopQvX-d: o_2
X-J3PopQvX-f: AyT1lAhyAQAA645HTYkhB4gLDM5zokBx1RSq1NMZ34yfPEFY650x2JWUiytPAWf_BDWcuH01wH8AAEB3AAAAAA==
X-J3PopQvX-z: p
Host: api.sahibinden.com
Connection: Keep-Alive
Accept-Encoding: gzip
With each request I want to be able to regenerate following headers:
X-J3PopQvX-a
X-J3PopQvX-b
X-J3PopQvX-c
X-J3PopQvX-d
X-J3PopQvX-f
X-J3PopQvX-z
I know of XMLHttpRequest but Im not sure how to use it in this case. I am new to node.js so a bit clueless
Edit:
I am able to send my headers using this : try {
let res = await httpClient.get(url, {
headers: headers,
params: query,
});
But I want to change j3pop headers everytime I send them. Need to change them manually. Is there any way for that?
Edit1:
This code here generates new headers:
function() {
'use strict';
console.log("inside");
var afterReadyCbCalled = false;
var originalHeaders = ["X-Origin-DC", "gytp","Cache-Control", "max-age=0","X-Forwarded-For", "103.255.4.53","X-Client-SrcPort", "45244","Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8","Accept-Language", "en-US,en;q=0.5","X-Forwarded-Proto", "https","X-TLS-Version", "771","Upgrade-Insecure-Requests", "1","ISTL-REFERER", "https://www.sahibinden.com/",];
var originalBody = "";
function afterReadyCb() {
if (afterReadyCbCalled) return;
afterReadyCbCalled = true;
var xhr = new XMLHttpRequest();
xhr.onload = function() {
var isValid = xhr.getResponseHeader("ISTL-INFINITE-LOOP");
if (isValid != null && isValid != '') return;
var a = xhr.getResponseHeader("ISTL-REDIRECT-TO");
if (a != null && a != '') {
location.replace(a);
} else {
if (window.history != null && typeof history.replaceState === 'function') {
var responseURL = xhr.responseURL != null ? xhr.responseURL : xhr.getResponseHeader("ISTL-RESPONSE-URL");
if (responseURL != null && responseURL != '') {
history.replaceState(null, '', responseURL);
}
}
document.open();
document.write(xhr.responseText);
document.close();
}
};
xhr.open("get", location.href, true);
for (var i = 0; i < originalHeaders.length; i += 2) {
var headerName = originalHeaders[i];
try {
xhr.setRequestHeader(headerName, originalHeaders[i + 1]);
} catch (e) {}
}
xhr.setRequestHeader("ISTL-INFINITE-LOOP", '1');
xhr.send(originalBody);
var evt = document.createEvent('Event');
evt.initEvent('QLpZFJdHv', true, true);
dispatchEvent(evt);
}
addEventListener('afterReady', afterReadyCb, false);
setTimeout(afterReadyCb, 400);
}());
Code is extracted from website by simply saving the html. Here is the link to website : https://www.sahibinden.com/
Here a sample code:
function doScrapRequest (postData, onSuccessCallback, onErrorCallback) {
var options = {
hostname: "your-host-name",
port: 443,
path: "/path-you-want-to-post-to",
method: 'POST',
headers: {
'X-J3PopQvX-a': '0JMyqk3j...',
'X-J3PopQvX-b': '-1o1lvb'
'X-J3PopQvX-c': 'AEC_kwhy...'
'X-J3PopQvX-d': 'o_2'
'X-J3PopQvX-f': 'AyT1lA...'
'X-J3PopQvX-z': 'p'
}
};
var req = https.request(options, function (res) {
res.setEncoding('utf8');
var body = '';
res.on('data', function (chunk) {
body = body + chunk;
});
res.on('end',function(){
console.log("Body :" + body);
if (res.statusCode != 200) {
onErrorCallback("Api call failed with response code " + res.statusCode);
} else {
// If you are expecting application/json you can do JSON.parse in the body variable.
onSuccessCallback(body);
}
});
});
req.on('error', function (e) {
console.log("Error : " + e.message);
onErrorCallback(e);
});
// write data to request body
req.write(postData);
req.end();
}
I am having issues with the amazon advertising api. I am using a nodejs library (https://github.com/humanstupidity/amazon-advertising-api) to fetch a report from amazon which returns me a body that seems to be in binary but I am not able to make it readable in JSON.
I tried the request in postman and it returns the same binary response. I have to download and unpacked the file from postman to make it readable but I am somehow not able to make it work in nodeJS.
This is the part inside the library which is important:
const request = require('request');
const util = require('util');
const requestPromise = util.promisify(request);
const postRequestPromise = util.promisify(request.post);
const getRequestPromise = util.promisify(request.get);
module.exports = class AdvertisingClient {
async getReport(reportId) {
while (true) {
let reportRequest = JSON.parse(await this._operation(`sp/reports/${reportId}`));
if (reportRequest.status === 'SUCCESS') {
return this._download(reportRequest.location);
}
await sleep(500);
}
}
_download(location, auth = true)
{
let headers = {}
if (auth) {
headers.Authorization = 'Bearer ' + this.options.accessToken;
}
if (this.options.profileId) {
headers['Amazon-Advertising-API-Scope'] = this.options.profileId;
}
let requestOptions = {
url: location,
headers: headers,
followRedirect: false,
gzip: true
}
return this._executeRequest(requestOptions);
}
async _executeRequest(requestOptions){
let response = await getRequestPromise(requestOptions);
if (response.statusCode == 307) {
let finalResult = await this._download(response.headers.location, false);
return finalResult;
}
let result={
success: false,
code: response.statusCode,
response: response.body,
requestId: 0
};
console.log(result);
if (!(response.statusCode < 400 && response.statusCode >= 200)) {
let data = JSON.parse(response.body);
if (data && data.requestId) {
requestId = data.requestId;
}
result = false;
} else {
result.success = true;
}
return result
}
async _operation(_interface, data, method = 'GET') {
let url = `https://${this.endpoint}/v2/${_interface}`;
let headers = {
'Authorization': 'Bearer ' + this.options.accessToken,
'Amazon-Advertising-API-ClientId': this.options.clientId,
'Content-Type': 'application/json',
}
if (this.options.profileId) {
headers['Amazon-Advertising-API-Scope'] = this.options.profileId;
}
let requestOptions={
url: url,
headers: headers,
method: method,
gzip: true,
}
if (method=="GET") {
requestOptions.qs=data;
}else{
requestOptions.json=data;
}
let response = await requestPromise(requestOptions)
let resData = response.body;
if (!resData.error) {
return resData;
} else {
throw resData.error;
}
}
}
I call the code via the function:
let reportResult = await client.getReport(reportID);
And this is the result I am getting:
{
success: false,
code: 200,
response: '\u001f�\b\u0000\u0000\u0000\u0000\u0000\u0000\u0000���j�#\u0010\u0006�{�B<�\u0010�������P�\u0016�[���M�F\r\u001a\u000b����\u0002y�nӖ�!�7����7�O\u001faRT�p�Fa\u0012g�8}�g�p\u0002H\\\u0019�H�����.M^��4ۗ���"�Z�\u0016q��I8��MR:��y3�\u001a/�F�P3\u0004�C�\u0017�t\\\u0017Y\u001a��\u001b��v��Hf��(`��0�+֧�g�8��]\u000b\u0019\u0013�\u001d-I\u001b.%��g��`���$���\u001f(��f~�tʐ�`H�/C���\u0011�>\u0014M\u0000�Fw\f��\u001b\u0018���\f�71`.���]Ev9[4\r1��5��!�˥�i\u0018�m�\u001c�R�=3��I�VL(����t�~sm_��\\i!\u0005\n' +
'�٠�aU���=��e�\u0007KW�Ypk�z(��Q��\u0003\u0013$`�em\u0010�\u0018=�d�����}���y3��\u000b.��=9\u0004\u0000\u0000',
requestId: 0
}
I played around with zlib as well but only get the error Error: unexpected end of file
I am pretty new to nodeJS and really have no idea what the issue is.
Thanks a lot in advance for your help!
The body is a gzip'ed (compressed) JSON. You need to gunzip it first.
If you use amazon-advertising-api-sdk package, it will do this automatically for you.
I am new to Nodejs .
I am trying to pass JWT token from Nodejs to java service class.
I am getting JWT token in a variable in Nodejs code that I need to pass to spring mvc application service class.
can anyone please help me on this?
And having confusion with how to integrate Nodejs with java if i pass variable from Nodejs to java?
Node code is,
module.exports = {
verifyReq: function (req, res, next) {
if (req.headers.authorization) {
res.setHeader('Content-Type', 'text/html');
res.write('<div id="_mscontent"><script src="URL"></script>');
var notAuthorized = false;
var authorization = req.headers.authorization;
console.log("authorization: " + authorization);
if (authorization) {
req.isAuthorized = true;
}
try {
var decodedJWT = JWT.decode(authorization.split(' ')[1], "", true);
} catch (e) {
notAuthorized = true;
}
else {
req.isAuthorized = false;
res.status(401);
res.end('Not Authorized!');
return;
}
return req.isAuthorized === true;
}
};
Java Code,
public class GetCarAssetValuesService {
private static String output;
private static String token;
private static Asset[] myObjects;
public void getAssets(String tokenToPass)
throws JsonParseException, JsonMappingException, IOException, JSONException {
System.out.println("In service");
HttpsURLConnection myURLConnection = null;
InputStream inputStream = null;
InputStreamReader inputStreamReader = null;
BufferedReader bufferedReader = null;
StringBuilder strBuilder = new StringBuilder();
JSONObject jsonObj = new JSONObject(tokenToPass);
System.out.println("success_token= " + jsonObj);
token = jsonObj.getString("access_token");
System.out.println("Print token= " + token);
try {
URL url = new URL(
"Third Party URL");
myURLConnection = (HttpsURLConnection) url.openConnection();
String bearerAuth = "Bearer " + token;
myURLConnection.setRequestProperty("Authorization", bearerAuth);
myURLConnection.setRequestMethod("GET");
myURLConnection.setRequestProperty("Content-Type", "application/json");
myURLConnection.setDoOutput(true);
inputStream = myURLConnection.getInputStream();
inputStreamReader = new InputStreamReader(inputStream);
bufferedReader = new BufferedReader(inputStreamReader);
if (myURLConnection.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : " + myURLConnection.getResponseCode());
}
System.out.println("Here the control cars...");
System.out.println("Output from Server .... \n");
while ((output = bufferedReader.readLine()) != null) {
strBuilder.append(output);
System.out.println(output);
}
myURLConnection.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
String mindsphereResponse = strBuilder.toString();
System.out.println("Responsesssssss" + mindsphereResponse);
ObjectMapper mapper = new ObjectMapper();
myObjects = mapper.readValue(mindsphereResponse, Asset[].class);
}
Here instead of passing "tokenToPass" i want to get this token from node js i.e.decodeJWT. This "tokenToPass" i am getting from other java service now i want it from Nodejs.
Thanks in Advance..!!!
You can set the JWT token in the HTTP Request header ( nodejs ) and API endpoint ( java ) can be get it from there.
HelloController.java
#Controller
public class HomeController {
#Autowire
private HomeService homeService;
#GetMapping("/hello")
public String home(HttpServletRequest request, Model model) {
helloService.invoke(request.getHeader('JWT_TOKEN_KEY'));
}
}
HelloService.java
#Service
public class HelloService {
public void invoke(jwtToken) {
// Use this jwttoken
}
}
NodeJS.js
var options = {
host: 'your_java_api_endpoint',
port: 80,
path: '/hello',
headers:{
'JWT_TOKEN_KEY':'json web token here'
}
};
http.get(options, function(res) {
res.on("data", function(responseData) {
console.log("data: " + responseData);
});
}).on('error', function(e) {
console.log("http error : " + e);
});
I need to make a HTTP GET request to foreign server to start receiving events. After request I immediately get multipart/x-mixed-replace response. When an event occurs, it's sent as XML message together with boundary indicating the end of this part.
Now I must implement it in Node.js. With normal request I use node-rest-client, call its get() method and put my logic in method's callback. Trouble is that callback is executed only when response is finished and with multipart/x-mixed-replace it isn't until connection closes.
Is there some other NPM module that does the trick? I searched NPM registry but results I found seem unappropriate to the task. Or is it better to do it in pure Node? I so, please provide an example.
Here is my own implementation:
const webStream = {
get: function (url, callback) {
let webClient;
if (url.startsWith("http://")) {
webClient = require("http");
} else if (url.startsWith("https://")) {
webClient = require("https");
} else {
throw "Unsupported protocol.";
}
let clientRequest = webClient.get(url, function (response) {
let context = {
url: url,
boundary: "",
contentType: "",
contentLength: 0
};
let headersCompleted = false;
let bodyCompleted = false;
let buffer = null;
let receivedBodyChunk = 0;
response.on("data", function (chunk) {
if (!headersCompleted) {
let headers = chunk.toString().split(/\r?\n/);
context.boundary = headers[0].substring(2);
context.contentType = headers[1].split(":")[1].trim();
context.contentLength = parseInt(headers[2].split(":")[1]);
buffer = Buffer.alloc(context.contentLength);
headersCompleted = true;
} else {
if (!bodyCompleted) {
if (receivedBodyChunk < context.contentLength) {
chunk.copy(buffer, receivedBodyChunk, 0, chunk.byteLength);
receivedBodyChunk += chunk.byteLength;
if (receivedBodyChunk === context.contentLength) {
bodyCompleted = true;
}
}
}
if (bodyCompleted) {
callback(buffer, context);
headersCompleted = false;
bodyCompleted = false;
buffer = null;
receivedBodyChunk = 0;
}
}
});
});
return {
url: url,
handler: clientRequest,
on: function (type, listener) {
clientRequest.on(type, listener);
},
abort: function () {
clientRequest.abort();
}
};
}
};
let stream = webStream.get("http://127.0.0.1:8090/", function (data, context) {
// data: Received content (Buffer)
// context: { url, boundary, contentType, contentLength }
// TODO: Do something here...
});
// stream.abort();
// stream.on("error", function(e) {
// console.log("Error: " + e.message);
// });
I have created Xamrin native shared project supporting Android and iOS mobile platforms. I want to consume REST services in both mobile apps. If I make request to REST API using HttpClient then it does not works. Gives me response as:
{StatusCode: 404, ReasonPhrase: 'Not Found', Version: 1.1, Content:
System.Net.Http.StreamContent, Headers: { Vary: Accept-Encoding
Server: DPS/1.0.3 X-SiteId: 1000 Set-Cookie: dps_site_id=1000; path=/
Date: Wed, 27 Jul 2016 12:09:00 GMT Connection: keep-alive
Content-Type: text/html; charset=utf-8 Content-Length: 964 }}
Content: {System.Net.Http.StreamContent} Headers: {Vary:
Accept-Encoding Server: DPS/1.0.3 X-SiteId: 1000 Set-Cookie:
dps_site_id=1000; path=/ Date: Wed, 27 Jul 2016 12:09:00 GMT
Connection: keep-alive } IsSuccessStatusCode: false ReasonPhrase:
"Not Found" StatusCode: System.Net.HttpStatusCode.NotFound Version:
{1.1} Non-public members:
If I uses HttpWebResponse to make request it successfully gets data.
Can you please tell why HttpClient is not working ?
// Using HttpClient
public async Task<string> GetCategories11(string token)
{
using (HttpClient client = new HttpClient())
{
var url = string.Format("{0}{1}", BaseUrl, CategoriesEndPoint);
var uri = new Uri(url);
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
try
{
using (var response = await client.GetAsync(uri))
{
if (response.IsSuccessStatusCode)
{
var contentStr = await response.Content.ReadAsStringAsync();
return contentStr;
}
else
return null;
}
}
catch
{
return null;
}
}
}
// Using HttpWebRequest
public async Task<ResponseModel> GetCategories(string token)
{
// Create an HTTP web request using the URL:
var url = string.Format("{0}{1}", RequestClient.BaseUrl, CategoriesEndPoint);
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri(url));
request.ContentType = "application/json";
request.Headers.Add("Authorization", "Bearer " + token);
request.Accept = "application/json";
request.Method = "GET";
try
{
// Send the request to the server and wait for the response:
using (HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync())
{
// Get a stream representation of the HTTP web response.
using (Stream stream = response.GetResponseStream())
{
// Use this stream to build a JSON object.
JsonValue jsonDoc = await Task.Run(() => JsonObject.Load(stream));
return new ResponseModel() { Success = true, ResponseValue = jsonDoc.ToString(), StatusCode = response.StatusCode };
}
}
}
catch (WebException ex)
{
using (var stream = ex.Response.GetResponseStream())
using (var reader = new StreamReader(stream))
{
return new ResponseModel() { ResponseValue = reader.ReadToEnd(), StatusCode = ((HttpWebResponse)ex.Response).StatusCode };
}
}
catch (Exception ex)
{
return new ResponseModel() { ResponseValue = ex.Message };
}
}
Debug through and pause on line using (var response = await client.GetAsync(uri)) what is uri? and it is the same as in GetCategories()?
If you prefer, this is the method I use from Xamarin.Android and it works with a bearer token. Change to suit your needs, you may not need to do the JsonConvert.DeserializeObject() part.
protected async Task<T> GetData<T>(string dataUri, string accessToken = null, string queryString = null)
{
var url = baseUri + "/" + dataUri + (!string.IsNullOrEmpty(queryString) ? ("?" + queryString) : null);
try
{
using (var httpClient = new HttpClient() { Timeout = new TimeSpan(0, 0, 0, 0, SharedMobileHelper.API_WEB_REQUEST_TIMEOUT) })
{
// Set OAuth authentication header
if (!string.IsNullOrEmpty(accessToken))
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
using (HttpResponseMessage response = await httpClient.GetAsync(url))
{
string content = null;
if (response != null && response.Content != null)
content = await response.Content.ReadAsStringAsync();
if (response.StatusCode == HttpStatusCode.OK ||
response.StatusCode == HttpStatusCode.Created)
{
if (content.Length > 0)
return JsonConvert.DeserializeObject<T>(content);
}
else if (response.StatusCode == HttpStatusCode.InternalServerError)
{
throw new Exception("Internal server error received (" + url + "). " + content);
}
else
{
throw new Exception("Bad or invalid request received (" + url + "). " + content);
}
}
}
}
catch (Exception ex)
{
Log.Error("Could not fetch data via GetData (" + url + ").", ex.ToString());
throw ex;
}
return default(T);
}