Json put/get/post in Restful webservices not working - json

I am trying to pass parameters to a server and extract the report in csv format. So the code i have has PUT/GET/POST in the order. I could get GET and POST work, but when i add PUT there is no error just blank screen.
String output1 = null;
URL url = new URL("http://<servername>/biprws/raylight/v1/documents/12345/parameters");
HttpURLConnection conn1 = (HttpURLConnection) url.openConnection();
conn1.setRequestMethod("PUT");
conn1.setRequestProperty("Accept", "application/json");
conn1.setRequestProperty("Content-Type", "application/json; charset=utf-8");
conn1.setDoInput(true);
conn1.setDoOutput(true);
String body = "<parameters><parameter><id>0</id><answer><values><value>EN</value></values></answer></parameter></parameters>";
int len1 = body.length();
conn1.setRequestProperty("Content-Length", Integer.toString(len1));
conn1.connect();
OutputStreamWriter out1 = new OutputStreamWriter(conn1.getOutputStream());
out1.write(body, 0, len1);
out1.flush();
What i am trying to do is pass parameter EN to the report and refresh it, take the output in csv using GET. POST is used for login to the server. I could make GET and POST work and get the output in CSV but not refreshed one.
Appreciate very much any help here.
Thanks,
Ak

What is the response code from the server when using PUT?
A PUT may not actually return a body to display on the screen; often times a PUT will only return a 200 or 204 response code. 204 would clearly mean that the server took the data and applied it, but is not sending you anything back, 200/201 may include a response, but maybe not. It depends on the folks who implemented the API.
https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html (section 9.6)
Should a RESTful 'PUT' operation return something

Related

HttpClient reads incomplete or malformed string

Im trying to figure out which part of my app (Xamarin Forms and proxy written in PHP) is buggy. Firstly I thought that my proxy (written in PHP) is working incorrectly with long set of data (ie. json containing 1.300.000 characters) and returns malformed response, but every single request with Postman gives me correct JSON, which is successfully decoded with third-party tools. So I assume, proxy is working well.
The problem is (I guess) with decoding response in my Xamarin Forms (2.0.0-beta.22) app. I'm using HttpClient to read response with this code:
response.EnsureSuccessStatusCode();
var entries = new List<HistoryEntry>();
var content = await response.Content.ReadAsStringAsync();
_loggerService.Error(content);
response is just GetAsync response from HttpClient. The problem is: content is randomly incomplete/malformed. Saying this I mean last character is missing (}) or JSON keys/values have additional " character, which breaks everything. Unfortunately, I can make exactly the same requests many times and once it works, once not. I found out that this behavior happens only with large set of data (as I mentioned before, long JSON string).
Is there any possibility that ReadAsStringAsync does not wait for full response or in any way alters my response string? How can I find the reason of wrongly downloaded data?
EDIT 21.05.2019:
Just copied valid JSON (available here: https://github.com/jabools/xamarin/blob/master/json.txt) and returned it from Lumen app by response()->json(json_decode(..., true)) and still the same result. Hope someone will be able to reproduce this and help me with this issue :( More informations in comments.
Used this code in C#:
Device.BeginInvokeOnMainThread(async () =>
{
for (int i = 0; i < 10; i++)
{
var response = await client.GetAsync("<URL_TO_PHP>");
//var response = await client.GetAsync("https://jsonplaceholder.typicode.com/photos");
var content = await response.Content.ReadAsAsync<object>();
Debug.WriteLine("Deserialized: " + i);
}
});

HMRC MTD Hello World with Qt

I have a Qt program that stores all my small (tiny) company information on a sql database and I have over the years tailored it to do all my accounting stuff, invoices, BOMs etc.
At the push of a button I can get all of the necessary sql data to calculate a quarterly VAT return, but we're going to have to electronically submit all the data now, not just calculate it. I have all the data needed, it's just a case of submitting over HTTP using json (of which I know a little/nothing about respectively).
I'm small enough so that I don't have to do this submission at the moment, but the time will likely come, so I'm trying the most basic of requests in the HMRC's sandbox as a starting point.
On this page it shows you how to do an hello world request in Java, so I'm trying to do the same with Qt with C++.
I've tried the following which responds to the push of a button and I have of course, set up a slot to deal with a response:
void MainWindow::hello()
{
QJsonObject json;
QString rs("https://test-api.service.hmrc.gov.uk/hello/world");
QNetworkRequest request
{
QUrl(rs)
};
request.setHeader(QNetworkRequest::ContentTypeHeader,"application/vnd.hmrc.1.0+json");
request.setUrl(QUrl(rs));
manager->get(request);
}
and the main window init:
manager = new QNetworkAccessManager();
QObject::connect
(manager, &QNetworkAccessManager::finished, this, [=](QNetworkReply *reply)
{
if (reply->error())
{
ui->debugText->appendHtml(reply->errorString());
return;
}
QString answer = reply->readAll();
ui->debugText->appendHtml(answer);
}
);
To which I get the reply:
Error transferring https://test-api.service.hmrc.gov.uk/hello/world -
server replied: Not Acceptable
I assume that means I am communicating with the sever now, but I do not know what this terse error message means!
The Java on the HMRC web page is as follows:
// construct the GET request for our Hello World endpoint
HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(
"https://test-api.service.hmrc.gov.uk/hello/world");
request.addHeader("Accept", "application/vnd.hmrc.1.0+json");
// execute the request
HttpResponse response = client.execute(request);
// extract the HTTP status code and response body
int statusCode = response.getStatusLine().getStatusCode();
String responseBody = EntityUtils.toString(response.getEntity());
Is that enough information for someone to point me in the right direction of what I'm doing wrong please? Suspect I am missing a fundamental point here.
In your Java example, you are setting the HTTP header "Accept". In your C++/Qt snippet, your are setting the "Content-Type" header.
You may want to adapt your code like this to match your Java working example:
QNetworkRequest request { QUrl(rs) };
request.setRawHeader(QByteArray("Accept"), QByteArray("application/vnd.hmrc.1.0+json"));
manager->get(request);

Polymer core-ajax won't post JSON?

I'm using core-ajax to retrieve JSON data just fine. Turning the component around to post back to the server as JSON is another thing altogether. In all cases, and irrespective of the contentType or handleAs parameters passed in, it appears that my JSON object I'm passing in as an input is being converted back to key=value in the server headers.
The code:
var ajax = document.querySelector('core-ajax');
ajax.method = 'POST';
ajax.handleAs = 'JSON';
ajax.contentType = 'application/json';
ajax.params = JSON.stringify(data);
ajax.go();
Really straightforward. The logs in Go give me:
2014/07/22 14:23:09 utils.go:139: OPTIONS /1/users/173?access_token=(token)
2014/07/22 14:23:09 utils.go:124: POST /1/users/173?access_token=(token)
2014/07/22 14:23:09 users.go:379: full_name=Greg%20Johnson
We've verified that there's no transformation happening on our side. Request headers are going out just fine.
I could completely be missing something. How else can we successfully POST out JSON data?
.params is for URL params. What you want is to post the JSON as the request body? For that, I believe you need to set the .body property:
This should do the trick:
ajax.body = data
See https://github.com/Polymer/core-ajax/blob/master/core-ajax.html#L151

BackgroundTransferRequest DownloadLocation to get the Response content

I am uploading a file to the server using BackgroundTransferRequest object. I need to access the response header sent from the server. Based on the research, I understand that there is no direct access to the Response of the request and one possible work around is to provide a download location to which the response content will be written.
However, when I try to do that, there is no data written to that file and its 0 bytes. My request server is actually sending a response having ONLY the headers (without any content).
So my question is, does the response have to have body in order to get the response written to the DownloadLocation?
My code sample:
var request = new BackgroundTransferRequest(targetUri)
{
DownloadLocation = new Uri(downloadTo, UriKind.Relative),
UploadLocation = new Uri(uploadFrom, UriKind.Relative),
Method = "POST"
};

IOS - How to handle return calls from a RESTful service API

I am using an API to have users create an account within my app.
Now I am able to generate the URL required in objective-C to submit the values and in the API documentation it has the return numbers that will confirm to me what has happened.
My question is how do I relay that information to the user of the app?
The return call is shown to me in a HTML page as plain text.
Any ideas?
Thanks in advance.
///////
2012-10-03 12:24:31.557 Multi Web[72631:15203] Dictionary list - {
Connection = "keep-alive";
"Content-Encoding" = gzip;
"Content-Length" = 26;
"Content-Location" = "signup.php";
"Content-Type" = "text/html";
Date = "Tue, 02 Oct 2012 23:24:32 GMT";
P3P = "policyref=\"/w3c/p3p.xml\", CP=\"ALL CURa ADMa DEVa OUR IND UNI COM NAV INT STA PRE\"";
Server = "Apache/2.2.14 (Ubuntu)";
Status = "200 OK";
TCN = choice;
Vary = "negotiate,Accept-Encoding";
"X-Limit-Key-Limit" = 10000;
"X-Limit-Key-Remaining" = 9992;
"X-Limit-Key-Reset" = 236;
"X-Limit-User-Limit" = 320;
"X-Limit-User-Remaining" = 319;
"X-Limit-User-Reset" = 3600;
"X-Powered-By" = "PHP/5.3.2-1ubuntu4.14";
I got this in my console so I now, I have created the account succesfully.
In the middle it says Status = "200 OK";
How do I use that particular line? If I can hook up a UIAlertView to that then i am where I want to be.
Cheers.
I'm not sure if your situation is related to this question. According to docs from the getPocket API you are using, i see the following:
According to apple docs, the default HTTP method is GET. What you need to do is check the response headers from the API. So what you need to do is change your httpMethod to HEAD like so:
NSMutableURLRequest *modReq = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"www.somesite.com/?something"]];
[modReq setHTTPMethod:#"HEAD"];
Then you can read the values from the header with something like so:
NSURLResponse* response = // the response, from somewhere
NSDictionary* headers = [(NSHTTPURLResponse *)response allHeaderFields];
You can then get the response values, and tell the user whats up accordingly.
It's called designing and creating a user interface.
You send a request to the server and get a response. Your job is to examine the response, recognise what it means, and tell the user in an appropriate way what the response meant. Since the user is not an expert in parsing html, showing the html would almost always be entirely inappropriate.
For a user entering a username and password correctly, the appropriate response is usually that the user can now access the site.