POSTing JSON with HttpsURLConnection & OutputStreamWriter fails - json

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.

Related

java.io.IOException: stream is closed

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
}

Add JSON data to MySQL database

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

Spring MVC either sending JSON or Redirecting to another page

Hello I have been using Spring 3 for my project, I have been stuck in on point.
if(ajax){
User user = userTemplate.getUser(form.getCreator_id());
int isPremium = user.getPremium();
if ( isPremium == 1 ){
Map<String,String> resultMap = new HashMap<String,String>();
response.setHeader("Access-Control-Allow-Headers", "*");
response.addHeader("Access-Control-Allow-Origin", "*");
resultMap.put("result", "success");
return new Gson().toJson(resultMap);
}else{
return "redirect:/f/redirectedUrl?url="+form.getWeb_page();
}
}
redirectedUrl controller is just for redirecting, but if the request is ajax request then i want to response the request as json.
How can I achieve this, thanks.
Edit : I can understand if request is ajax or not. My problem is if it is ajax i want to response json, if it is not then i want to redirect.
Use this code in your controller to identify if request is ajax or not and based on that you can add your logic.
boolean ajax = "XMLHttpRequest".equals(
getRequest().getHeader("X-Requested-With"));
You can decide it from header("X-Requested-With") of your httpRequest object.
public ModelAndView getDetails(HttpServletRequest request, HttpServletRespone response) {
if(ajax) {
try {
new MappingJacksonHttpMessageConverter().write(object, MediaType.APPLICATION_JSON, new ServletServerHttpResponse(response));
} catch(Exception e) {
logger.error("Error when converting to json");
}
return null;
} else {
return new ModelAndView("viewName");
}
}

My Windows Phone app Get empty response (404 Not Found) Scond time, work's great first time;And always work fine if without SSL

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.

Limitations retrieving JSON String from web service using MonoTouch

I am developing an iOS Application using MonoTouch. The application collects its data from a web service, using this code:
private static string getResult (string url)
{
string result;
var request = HttpWebRequest.Create (url);
request.ContentType = "application/json";
request.Method = "POST";
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
if (response.StatusCode != HttpStatusCode.OK)
Console.Out.WriteLine("Error fetching data. Server returned status code: {0}", response.StatusCode);
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
result = reader.ReadToEnd();
}
}
return result;
}
And this works fine, BUT when the json string returned from the Web Service reaches a certain size, the request returns with Internal server error 500. I have tried to invoke the service method directly in a web browser, and this returns a json string as expected. Why will it not work with my code, and is there a way to fix this?
Update:
I think this might solve my problem: http://forums.iis.net/t/1176077.aspx/1
Try Increasing Time Out for your service request. Your service must be timing out resulting 500 error
Also check this http://www.checkupdown.com/status/E500.html