Rectangle 27 9

Thanks to Audrius's comments I tracked a possible source of the problem to the interaction between uWSGI and nginx: apparently, if you receive POST data in a request you must read it before returning a response.

@app.route('/jsonpost', methods=['GET', 'POST'])
def json_post():
    if request.method == 'POST':
        dummy = request.form
    resp = make_response('{"test": "ok"}')
    resp.headers['Content-Type'] = "application/json"
    return resp
--post-buffering 1

I still don't understand why the problem does not present itself with Content-Type set to "text/html"

"if you POST, you must read the data". you my friend are a legend. apologies for posting this, but it has cost me several hours!!!!! +1 thanks bah humbug!!

python - No response with POST request and Content-Type "application/j...

python json post http-headers flask
Rectangle 27 6

Example of sending an HTTP request and reading back the HTTP response:

String res = "";
String url = "http://www.domain.com/youscript.php";
URL urlObj = new URL(url);
URLConnection lu = urlObj.openConnection();


// Send data - if you don't need to send data 
// ignore this section and just move on to the next one
String data = URLEncoder.encode("yourdata", "UTF-8");
lu.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(lu.getOutputStream());
wr.write(data);
wr.flush();

// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(lu.getInputStream()));
String line = "", res = "";
while ((line = rd.readLine()) != null) {
  res += line;
}

wr.flush();
wr.close();
System.out.println(res);

So to incorporate this into how I'm already doing it, I can just use a buffered reader on the InputStream I have already and that would work?

@RaidenXL yes. it worked for me on my app. I believe that you can use the getEntity() option too, but I don't have any experience with it so I can't help you with that.

java - recieving HTTP POST echo response from a PHP file (sending the ...

java php android http-post echo
Rectangle 27 6

Example of sending an HTTP request and reading back the HTTP response:

String res = "";
String url = "http://www.domain.com/youscript.php";
URL urlObj = new URL(url);
URLConnection lu = urlObj.openConnection();


// Send data - if you don't need to send data 
// ignore this section and just move on to the next one
String data = URLEncoder.encode("yourdata", "UTF-8");
lu.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(lu.getOutputStream());
wr.write(data);
wr.flush();

// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(lu.getInputStream()));
String line = "", res = "";
while ((line = rd.readLine()) != null) {
  res += line;
}

wr.flush();
wr.close();
System.out.println(res);

So to incorporate this into how I'm already doing it, I can just use a buffered reader on the InputStream I have already and that would work?

@RaidenXL yes. it worked for me on my app. I believe that you can use the getEntity() option too, but I don't have any experience with it so I can't help you with that.

java - recieving HTTP POST echo response from a PHP file (sending the ...

java php android http-post echo
Rectangle 27 1

username = mUsername.getText().toString();
            password = mPassword.getText().toString();
            mResult.setText(username + ":" + password);
            mCombination = username + ":" + password;
            byte[] byteArray = new byte[0];
            try {
                byteArray = mCombination.getBytes("UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

            final String base64 = Base64.encodeToString(byteArray, Base64.NO_WRAP);
            mEncoded.setText(base64);

Post JSON data and receive response in android - Stack Overflow

android json post httpurlconnection
Rectangle 27 0

Ok, you need the form with the username and password, so, you'll be able of retrieve the user and login from the third party web. When you'll have it, you need to send a cURL petition with this data as the third party do. I mean, go to the 3rd party web, and inspect the form. If the form is sending the post data to 'logInUser.php' with the post data being 'usergame=USERNAME&passgame=PASSWORD' you'll have to POST your form data against 'logInUser.php' with the data in the same format as the web do.

Problem is, would your users give you their passwords? Because if you want to use cURL to login to the other web, you'll need their username and password.

You should check if the web has Oauth (http://oauth.net/), and if so, you should use it.

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

forms - PHP Posting to external script and receiving response - Stack ...

php forms curl request response
Rectangle 27 0

Thanks to Audrius's comments I tracked a possible source of the problem to the interaction between uWSGI and nginx: apparently, if you receive POST data in a request you must read it before returning a response.

@app.route('/jsonpost', methods=['GET', 'POST'])
def json_post():
    if request.method == 'POST':
        dummy = request.form
    resp = make_response('{"test": "ok"}')
    resp.headers['Content-Type'] = "application/json"
    return resp
--post-buffering 1

I still don't understand why the problem does not present itself with Content-Type set to "text/html"

python - No response with POST request and Content-Type "application/j...

python json post http-headers flask
Rectangle 27 0

i think your request should be in GET method not in post for above case.Try to change to do this request in GET instead of post.

javascript - unable to receive response from ajax post request using s...

javascript php html ajax slim
Rectangle 27 0

If the POST request succeeded:

When you receive a response for a POST request, first check the status code.

If status code equals 200 (OK) or 204 (No Content) the response body is likely empty or it describes the result of the operation. With either status codes, the request hasn't created a resource which can be identified by a URI.

If status code equals 201 (Created) the request created a resource on the server and the response body may describe the result of the operation, and the response should contain a location header where the new resource can be located.

Usually, the web service API describes the details about the response body (if any) and its content type and character encoding. Possibly, there are more than one format that can be send, e.g. JSON or XML.

The server will send a corresponding status code and optionally a response body containing details about the error. Oftentimes, the server may send a response body in a content type which does not match the Accept header of the request.

A client should always also check the content type of the response body (if any) and decode it accordingly. In case of server errors, the content type may often be text/html instead in the content type specified in the Accept header, e.g. application/json.

So, if you log the complete error description for Cocoa error 3840 you will read that the given text is likely not JSON since it must start either with a '[' or '{'. This indicates, that you got an error message from the server which is not JSON. Decode the error message so that it is human readable and log it to the console to see what the server is telling you.

OK, the AFJSONREquestOperation fails but operation status code is still 200. I dont know why it fails. Thanks Ill try and find out whats happening.

AFJSONRequestOperation expects JSON as response. Thus, it's not that suitable when your response is somewhat "nonchalant" to what you expect. Your web service behavior may also not be correct. Use a lower level class of AFNetworking or just implement your POST request directly with NSURLConnection, and decode the response depending on the Content-Type of the response.

ios - Why is json response NULL when I send video file larger than 20M...

ios post json
Rectangle 27 0

I cant speak authoritatively to ember-data (though I know enough to assert that it certainly supports the HTTP POST verb), except to quote the docs:

Without any configuration, Ember Data can load and save records and their relationships served via a RESTful JSON API, provided it follows certain conventions.

If you need to integrate your Ember.js app with existing JSON APIs that do not follow strong conventions, Ember Data is designed to be easily configurable to work with whatever data your server returns.

The 'certain conventions' that Ember Data refers to above is a bit of a moving target, but the Ember team is close to codifying that definitively (see jsonapi.org).

Also from that doc:

For simple applications, you can get by using jQuery to load JSON data from a server, then use those JSON objects as models.

App.examplePost = function () {
    return Em.$.ajax('http://example.com/api/serviceXYZ', {
        "type": 'POST', // HTTP method
        "dataType": 'JSON', // type of data expected from the API response
        "data": { // Begin data payload
            "auth": {
                "type" : "basic",
                "password": "xxx",
                "username": "someone"
            },
            "requestId" : 15,
            "method": {
                "name": "getUserAvailabilityAndInfo",
                "params": {
                    "userId" : "000",
                    "peopleOnly" : "1"
                }
            }
        }, // End data payload
        "success": function (data, textStatus, jqXHR) {
            return data;
        },
        "error": function (jqXHR, textStatus, errorThrown) {
            window.console.log(jqXHR);
        }
    });
};

(See the standard jquery ajax() docs for more details on the above.)

In an appropriate route definition, we would override the default model() method:

App.ExamplePostRoute = Ember.Route.extend({
    model: function (params) {
        return App.examplePost();
    }
});

To see the model hook in action, you'd navigate to the route path that maps to the 'examplePost' route state via its associated URL (e.g., http:/myemberapp.example.com/#/examplePost). Because our ajax call executed by App.examplePost() eventually returns the API data on a fulfilled Promise (see the success() function), the model hook knows to use that response as its model object (and it knows how to do this asynchronously using promises).

An even more artificial example would be to override the default setupController() method, also in the route definition.

App.ExamplePostRoute = Ember.Route.extend({
    setupController: function (controller, model) {
        return App.examplePost().then(
            function (data) {
                controller.set(model, data);
            }
        );
    }
});

The setupController route method (which is always called, whether or not you transition to a route state via URL or other transition method) does not know about promises, hence the .then() usage above.

Again, you'd not normally statically load a literal model every time you enter a route state, but it's a way to get started, and with the Chrome Ember Inspector, will help you to prove that in fact this can work! Also, jquery and promises are a complicated subject, and in practice if you rolled your own client API code, you'd want to cast jquery's promise object into a standard promise object (see promises.org) via Ember.Deferred.promise(), for example. This is beyond the scope of this question, but FYI for your near-future explorations.

javascript - Using Ember.js to Receive JSON API in Server Response fro...

javascript ajax ember.js ember-data
Rectangle 27 0

i go with this tutorial androidhub4you.com/2012/09/. but now i got response in json, now i want to get those response in string how could i get it?

How to post and receive response from web services using JSON in andro...

android
Rectangle 27 0

Have you been able to see what your args look like on the receiving end?

To the point of Rookies answer - could it have something to do with how you're passing your postfields? Generally the postfield param will expect key value arrays or urlencoded strings (key1=val1&). Without a "key" to your JSON ($data_string) "value" does the server know how to accept the postfields? Could you maybe try the following?

// Personal preference here - arrays are easier for me to read
// Create a multi dem array dictionary with your values
$_dictionary = array("jsonrpc"=>"2.0",
                     "method" =>"login",
                     "id"     =>1,
                     "params" =>array("params"=>array("username"=>"4321","password"=>"1234"))
                    );

// json_encode 
$_dictionary = json_encode($_dictionary);

// your $data_string variable will now be in key=value  
$data_string = "mydata={$_dictionary}";

// set $data_string to your CURLOPT_POSTFIELDS...

POST JSON with PHP cURL and show JSON response - Stack Overflow

php json curl
Rectangle 27 0

Your PersonSheets has a property int Id, Id isn't in the post, so modelbinding fails. Make Id nullable (int?) or send atleast Id = 0 with the POst .

jquery - Send JSON data via POST (ajax) and receive json response from...

jquery ajax asp.net-mvc json
Rectangle 27 0

Use method as argument to load

Ion.with(getActivity())
   .load("POST",URLStr)
   .addQuery("action", "dummyAction")
   .addHeader("Content-Type", "application/json")
   .setLogging("ION_VERBOSE_LOGGING", Log.VERBOSE)
   .setJsonObjectBody(jsonStr)
   .asJsonObject()
   .setCallback(new FutureCallback<JsonObject>() {
       @Override
       public void onCompleted(Exception e, JsonObject result) {}
   });

Android koush/ion lib unable to post and receive JSON response - Stack...

android android-networking ion ion-koush
Rectangle 27 0

This is a newer conventional way (Ember 2.x) in dealing with API requests and responses and thus response payload/data, without relying on ember-data as ember-ajax ver 2 can be used directly and it's meant to replace the Ember.$.ajax API.

Using the ajax service exposed through ember-ajax/services/ajax, one might send requests and handle responses as such:

import Ember from 'ember';

export default Ember.Controller.extend({
  ajax: Ember.inject.service(),
  actions: {
    someAction(someObject) {
      let payload = { foo: Ember.get(someObject, 'someProperty') };
      this.get('ajax').post('/url', {
        data: payload
      }).then(({ response }) => {
        ...
        // handle response;
      });
    }
  }
});

javascript - Using Ember.js to Receive JSON API in Server Response fro...

javascript ajax ember.js ember-data
Rectangle 27 0

This is a simple way of making a post request and receiving a response in JSON for future parse:

internal static async Task<String> GetHttpPostResponse(HttpWebRequest request, string postData)
    {
        String received = null;

        request.Method = "POST";
        request.ContentType = "application/x-www-form-urlencoded";

        byte[] requestBody = Encoding.UTF8.GetBytes(postData);

        // ASYNC: using awaitable wrapper to get request stream
        using (var postStream = await request.GetRequestStreamAsync())
        {
            // Write to the request stream.
            // ASYNC: writing to the POST stream can be slow
            await postStream.WriteAsync(requestBody, 0, requestBody.Length);
        }

        try
        {
            // ASYNC: using awaitable wrapper to get response
            var response = (HttpWebResponse)await request.GetResponseAsync();
            if (response != null)
            {
                var reader = new StreamReader(response.GetResponseStream());
                // ASYNC: using StreamReader's async method to read to end, in case
                // the stream i slarge.
                received = await reader.ReadToEndAsync();
            }
        }
        catch (WebException we)
        {
            var reader = new StreamReader(we.Response.GetResponseStream());
            string responseString = reader.ReadToEnd();
            Debug.WriteLine(responseString);
            return responseString;
        }

        return received;
    }

'System.Net.HttpWebRequest' does not contain a definition for 'GetRequestStreamAsync' and no extension method 'GetRequestStreamAsync' accepting a first argument of type 'System.Net.HttpWebRequest' could be found (are you missing a using directive or an assembly reference?) this is the error im getting

Please install the Microsoft HTTP Client Library from NuGet and that should solve your problem.

@Meneses, Microsoft HTTP Client Library seems to be for wp8.1 and not wp8

@eeadev You seem to be right regarding the current version. If you want to use it in Windows Phone 8, you can always use the NuGet command Install-Package Microsoft.Net.Http -Version 2.2.19 as this version still supports Windows Phone 8.

@Meneses, I am new to C#, what would be the clause using in this case?

c# - How to Send POST Request in windows Phone 8 and get its Response ...

c# post windows-phone-8 windows-phone
Rectangle 27 0

I cant speak authoritatively to ember-data (though I know enough to assert that it certainly supports the HTTP POST verb), except to quote the docs:

Without any configuration, Ember Data can load and save records and their relationships served via a RESTful JSON API, provided it follows certain conventions.

If you need to integrate your Ember.js app with existing JSON APIs that do not follow strong conventions, Ember Data is designed to be easily configurable to work with whatever data your server returns.

The 'certain conventions' that Ember Data refers to above is a bit of a moving target, but the Ember team is close to codifying that definitively (see jsonapi.org).

Also from that doc:

For simple applications, you can get by using jQuery to load JSON data from a server, then use those JSON objects as models.

App.examplePost = function () {
    return Em.$.ajax('http://example.com/api/serviceXYZ', {
        "type": 'POST', // HTTP method
        "dataType": 'JSON', // type of data expected from the API response
        "data": { // Begin data payload
            "auth": {
                "type" : "basic",
                "password": "xxx",
                "username": "someone"
            },
            "requestId" : 15,
            "method": {
                "name": "getUserAvailabilityAndInfo",
                "params": {
                    "userId" : "000",
                    "peopleOnly" : "1"
                }
            }
        }, // End data payload
        "success": function (data, textStatus, jqXHR) {
            return data;
        },
        "error": function (jqXHR, textStatus, errorThrown) {
            window.console.log(jqXHR);
        }
    });
};

(See the standard jquery ajax() docs for more details on the above.)

In an appropriate route definition, we would override the default model() method:

App.ExamplePostRoute = Ember.Route.extend({
    model: function (params) {
        return App.examplePost();
    }
});

To see the model hook in action, you'd navigate to the route path that maps to the 'examplePost' route state via its associated URL (e.g., http:/myemberapp.example.com/#/examplePost). Because our ajax call executed by App.examplePost() eventually returns the API data on a fulfilled Promise (see the success() function), the model hook knows to use that response as its model object (and it knows how to do this asynchronously using promises).

An even more artificial example would be to override the default setupController() method, also in the route definition.

App.ExamplePostRoute = Ember.Route.extend({
    setupController: function (controller, model) {
        return App.examplePost().then(
            function (data) {
                controller.set(model, data);
            }
        );
    }
});

The setupController route method (which is always called, whether or not you transition to a route state via URL or other transition method) does not know about promises, hence the .then() usage above.

Again, you'd not normally statically load a literal model every time you enter a route state, but it's a way to get started, and with the Chrome Ember Inspector, will help you to prove that in fact this can work! Also, jquery and promises are a complicated subject, and in practice if you rolled your own client API code, you'd want to cast jquery's promise object into a standard promise object (see promises.org) via Ember.Deferred.promise(), for example. This is beyond the scope of this question, but FYI for your near-future explorations.

javascript - Using Ember.js to Receive JSON API in Server Response fro...

javascript ajax ember.js ember-data
Rectangle 27 0

Are you sure you have a valid android token on the server site? It's just a random thought, but I had a similar issue some time ago ;)

I cannot belive that - my code was all right all along but the problem is that my server_client_id from google was wrong at the webservice. You have saved me a lot of work! Thanks

Post JSON data and receive response in android - Stack Overflow

android json post httpurlconnection
Rectangle 27 0

I think you'll have a lot more success if you try using OkHttp, an HTTP client for Android made by Square developers. It adds a layer of abstraction so you don't have to write so much code for a simple POST request. Here is an example of the code for POST request to a server:

public static final MediaType JSON
    = MediaType.parse("application/json; charset=utf-8");

OkHttpClient client = new OkHttpClient();

String post(String url, String json) throws IOException {
  RequestBody body = RequestBody.create(JSON, json);
  Request request = new Request.Builder()
      .url(url)
      .post(body)
      .build();
  Response response = client.newCall(request).execute();
  return response.body().string();
}

(I would add this as a comment, but I don't yet have the SO rep)

Post JSON data and receive response in android - Stack Overflow

android json post httpurlconnection
Rectangle 27 0

Pass in the POJO object directly. Ion will automatically serialize it into JSON for you.

I tried it and it's still giving me same error. <br/> My POJO is public class UserBasicInfo extends User implements Serializable { } ` public class User implements Serializable { } `

An actual stack trace of this exception you are receiving would be helpful. And also the class definition as well, if you can provide that. The exception may be enough though.

Thanks, I'll put together a test case. Any chance you can share the stack trace of the error you are seeing? I don't see one in what you pasted.

Hi, Koush, I added the stackTrace, this is the only log which is getting printed.

Android koush/ion lib unable to post and receive JSON response - Stack...

android android-networking ion ion-koush
Rectangle 27 0

Your PersonSheets has a property int Id, Id isn't in the post, so modelbinding fails. Make Id nullable (int?) or send atleast Id = 0 with the POst .

jquery - Send JSON data via POST (ajax) and receive json response from...

jquery ajax asp.net-mvc json