I am getting below error when i am trying to print response from http connection. I think i am using the stream twice and for this reason it says stream is closed but not sure.
The error is coming on the writeInstFile() method where i am trying to print response using getInputStream().getText()
I just wanted to create new string variable and put the connection stream response in that variable and print it so that i can see what response i am getting when i try to do http request:
private void writeInstFile(File outFile) {
Properties config = workflowEnvironment.getConfig()
//http connection to get Authentication token
HttpURLConnection connection = connection("https://XXX/RequestToken")
if (connection.responseCode == HTTP_OK) {
String authToken = authTokenFromJson(jsonFromDssRequestTokenConnection(connection))
log.info("Authentication token: $authToken")
println(connection.getInputStream().getText());
if (connection.responseCode == HTTP_OK) {
println("Got http response code: ${connection.responseCode}, message: ${connection.responseMessage}")
log.info("Successful DSS request to ${connection.getURL()}")
LazyMap json = jsonFromDssExtractionConnection(connection)
.....
}
private static String authTokenFromJson(LazyMap json) {
json.value
}
private static LazyMap jsonFromDssRequestTokenConnection(HttpURLConnection connection) {
connection.inputStream.withCloseable { inStream ->
new JsonSlurper().parse(inStream as InputStream)
} as LazyMap
}
Related
Angular service.ts:
getExcel() {
let link: string = (this.url);
return link;
}
component.ts:
public getExcel() {
//checks if string is empty, undefined or not null
if (this.langCode) {
return window.open(this.avrs.getExcel());
}
}
Java rest.java
#GET
#Path("/excel")
#Produces("application/vnd.ms-excel")
public Response getTransportCostsExcel(
#Context HttpServletRequest request,
) {
byte[] excelInBytes = excelGen.getExcel();
if(excelInBytes == null){
return Response.status(Response.Status.NOT_FOUND).entity("No data").build();
}
//Header details
String contentType = "application/vnd.ms-excel";
Response.ResponseBuilder responseBuilder = javax.ws.rs.core.Response.ok((Object) excelInBytes);
responseBuilder.type(contentType);
responseBuilder.header("Content-Disposition", "attachment; filename=" + fileName);
//Returns Excel
return responseBuilder.build();
}
When I try calling my api from postman i get "No data" and status is 401 not found. So the rest method works fine.
I get my excel file if data is found. But I can't seem to handle the 401 response. Angular opens a new window and says
site not avaliable: ERR_INVALID_RESPONSE
As you can see im not using http.get cause I want the user to start downloading the excel if the file is found.
I'm developing a Grails concert application where I am acquiring the actual events from bandsintown.com using AngularJS.
$.getJSON("http://api.bandsintown.com/events/search.json?&api_version=2.0&app_id=FYP&location=Dublin,Ireland", function(result)
I am able to retrieve the events and I now want to turn each event into an object and add them to my database, so I can have a unique page for each event with their subsequent details and whatnot.
Is anyone able to provide me guidance on how to do such a thing?
Thank you!
I wrote something a while ago as a plugin which may help you get your head around what you need to do :
private String viewTicketField(String jiraserver, String jirauser,String jirapass, String url, String customField) {
if (url.endsWith('undefined')) {
return
}
String output=''
try {
HBuilder hBuilder=new HBuilder()
RESTClient http = hBuilder.httpConn(jiraserver, jirauser, jirapass,httpConnTimeOut,httpSockTimeOut)
http.request(Method.GET ) { req ->
uri.path = url
response.success = { resp, json ->
log.info "Process URL Success! ${resp.status} "
def result=JSON.parse(json.toString())
if (result.fields."customfield_${customField}") {
output=result.fields."customfield_${customField}"
}
}
response.failure = { resp ->
log.error "Process URL failed with status ${resp.status}"
}
}
}
catch (HttpResponseException e) {
log.error "Failed error: $e.statusCode"
}
return output
}
HBuilder class can be found in src
After you have connected and got back your JSON response you then parse each line
You create a new domain class
String url
String datetime
String app_id
String ticket_url
... and so on this is an entire entry from above url so for each key that you actually require put in domain class as strings then parse each iteration with above code
{"id":13926481,"url":"http://www.bandsintown.com/event/13926481?app_id=FYP","datetime":"2017-02-23T17:00:00","ticket_url":"http://www.bandsintown.com/event/13926481/buy_tickets?app_id=FYP\u0026came_from=233","artists":[{"name":"Rackhouse Pilfer","url":"http://www.bandsintown.com/RackhousePilfer","mbid":null}],"venue":{"id":3334537,"url":"http://www.bandsintown.com/venue/3334537","name":"Convention Centre","city":"Dublin","region":"07","country":"Ireland","latitude":53.3500292,"longitude":-6.2385286},"ticket_status":"unavailable","on_sale_datetime":null
I am building my first windowsPhone 8.1 application ,the role of my application is to create connection with server to get information from it, so I am writing the code to do this process by sending json-rpc request to server to get some information ,I am successful to get it in first time but when I send the second request I am receiving an empty response with 404 error (page not found).
But when I call the service without https (http only) it works fine regardless how many time I call it !
public async Task<string> GetDataFromServer(string urlToCall, string JSONData,string RR)
{
string UserName = “XXXXXXX”
string Password = "XXX";
using ( var handler = new HttpClientHandler())
{
handler.Credentials = new NetworkCredential(UserName, Password);
HttpClient client = new HttpClient(handler);
HttpResponseMessage response = null;
try
{
response = await client.PostAsync(urlToCall, new StringContent(JSONData.ToString(), Encoding.UTF8, " application/json"));
string res = response.Content.ReadAsStringAsync().Result;
Windows.UI.Popups.MessageDialog g = new Windows.UI.Popups.MessageDialog(res);
await g.ShowAsync();
return res;
}
catch (Exception ex)
{
Windows.UI.Popups.MessageDialog g = new Windows.UI.Popups.MessageDialog("Error is : " + ex.Message);
g.ShowAsync();
return "Error";
}
finally
{
response.Dispose();
client.CancelPendingRequests();
client.Dispose();
handler.Dispose();
}
}
}
Again, when call the URL of service (start with https) on first time I got response with seeked data, but second time I receive an empty response with 404 error (page not found) !!
Any help please
Please try to use this solution.
public async Task<string> SendJSONData3(string urlToCall, string JSONData)
{
string UserName = "XXXXXXXXX";
string Password = "XXXXXXXXX";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(urlToCall);
httpWebRequest.Credentials = new NetworkCredential(UserName, Password);
httpWebRequest.ContentType = "text/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(await httpWebRequest.GetRequestStreamAsync()))
{
string json = JSONData;
streamWriter.Write(json);
streamWriter.Flush();
}
var httpResponse = (HttpWebResponse)await httpWebRequest.GetResponseAsync();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
return result;
}
}
A couple of ideas:
Do not use the .Result property. Just use await instead to avoid deadlocks.
Remove the additional space in front of the media type parameter " application/json"
Enable logging on the webserver and see if the second request arrives on the server.
Get a network trace, for example with Wireshark or Fiddler.
Try puting WebRequest.RegisterPrefix("https://", WebRequestCreator.ClientHttp); in your initialization code, as proposed in this answer.
When unit testing, I want to check csv formatted results, so I have the following code in my test.
MyDtoReq request = new MyDtoReq();
// ... assign some properties
string url = request.ToUrl("GET");
HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(url);
httpReq.Accept = "text/csv";
csv = new StreamReader(httpReq.GetResponse().GetResponseStream()).ReadToEnd();
That works fine, if the request succeeds. But when it fails, it raises a System.Net.WebException that doesn't have the expected WebServiceException.ResponseStatus details. NUnit reports the exception as follows:
Test Name: TestReq
Test FullName: [...].TestReq
Test Source: c:\Users\[...]\UnitTestProject1\ServiceTests.cs : line 261
Test Outcome: Failed
Test Duration: 0:00:27.104
Result Message: System.Net.WebException : The remote server returned an error: (400) Bad Request.
Result StackTrace: at [...].TestReq() in c:\Users\[...]\UnitTestProject1\ServiceTests.cs:line 287
Turns out that this is by design, as most clients requesting csv format are not able to parse a ResponseStatus. In order to see the actual error, I would re-submit the request with format=html in the browser - a frustrating waste of time.
Here's how to get the actual error message from failing csv format requests:
// Declared in test setup
public const string Host = "http://localhost:1337";
private const string BaseUri = Host + "/";
[Test]
public void TestMyDtoReqCsvFormat()
{
MyDtoReq request = new MyDtoReq();
request.startDate = "20130919";
request.endDate = "20130930";
request.source = "Token";
try
{
string requestUrl = request.ToUrl("GET");
HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(requestUrl);
httpReq.Accept = "text/csv";
var csv = new StreamReader(httpReq.GetResponse().GetResponseStream()).ReadToEnd();
// assert some facts about the contents of csv
}
catch (Exception)
{
try {
JsonServiceClient client = new JsonServiceClient(BaseUri);
MyDtoReqResponse response = client.Get(request);
// do something if re-request succeeds (i.e. was a transient error)
}
catch (WebServiceException webEx)
{
var message = webEx.ResponseStatus.ErrorCode +
" " + webEx.ResponseStatus.Message.Trim() +
" " + webEx.ResponseStatus.StackTrace.Trim();
throw new WebException(message,webEx);
}
catch (Exception otherEx) {
System.Diagnostics.Debug.WriteLine(otherEx.Message);
throw new Exception(otherEx.Message, otherEx);
}
}
}
I'm using Processing 2.0.2 and importing java's java.net,javax.net, and java.io classes.
I'm trying to send a JSONObject to "https://www.bitstamp.net/api/balance/".
The JSONObject contains login info. I create it with this function:
JSONObject BitstampLoginJSON() {
JSONObject loginJSON = new JSONObject();
loginJSON.setString("password", "mypassword");
loginJSON.setString("user", "username");
return loginJSON;
}
I setup my connection successfully and then pass the connection to this function to send the request.
void SendBitstampBalanceRequestFromConnection(HttpsURLConnection givenCon) {
try {
givenCon.setDoOutput(true);
givenCon.setDoInput(true);
givenCon.setRequestProperty("Content-Type", "application/json");
givenCon.setRequestProperty("Acccept", "application/json");
givenCon.setRequestMethod("POST");
givenCon.connect();
OutputStreamWriter requestSender = new OutputStreamWriter(givenCon.getOutputStream());
String JSONString = BitstampLoginJSON().toString();
requestSender.write(JSONString);
requestSender.flush();
requestSender.close();
}
catch(IOException e) {
e.printStackTrace();
}
}
I get a response code 200 and returned message of "OK". Bitstamp returns a JSON Object that says this:
"error": "Missing user and/or password POST parameters"}
I'm quite confused as to why Bitstamp is not receiving or accepting my JSONObject. I have read about a half dozen posts on SO about JSON and POSTing but I can't seem to get it.