简体   繁体   中英

How to use Phonegap Plugins(For Android) to make simple json post request to API?

I am a beginner in Android programming, so please bare with me.I want to use the following Phonegap Plugin( cordova-HTTP ) to make post request to a remote api( https://api.somewebsite.com/androidMobile.aspx and passing it name=getJsonData and type=2f)and get the response back to JavaScript.(call the plugin from JavaScript)

I would appreciate if an expert shows me how to use the above Plugin to make post request and receive json response back in JavaScript for further processing.I have never used Phonegap Plugin before so I need some step by step guide here.Thanks in advance.

Note: I already know how to make post request using Ajax but it is requirement to use native code to make post request. I did lots of research on the internet and most developer suggest using Phonegap Plugins instead of learning how to make JavaScript and Java communicate with each other.But i couldn't find any beginner step by step guide on how to use simple Phonegap Plugin for post request to server!

Phonegap plugin that need help with:

https://github.com/wymsee/cordova-HTTP

Post request information:

user-agent:Mozilla/5.0 (Linux; Android 4.0.4; en-gb; SM-T330 Build/IMM76D) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Safari/533.1

API URL: https://api.somewebsite.com/androidMobile.aspx

posting data to API :name=getJsonData,type=2f

API response sample:

{
    "resp": [{
        "Season": "2",
        "Description": "New Models are all green"
    }]
}

Phonegap javascript:

function onButtonClick(id) {
    var strQuery = "";     
        strQuery = "?name=getJsonData&type=2";
        POSTCall("getJsonDataCallBack", "OnError", strQuery);

}

function POSTCall(onSuccess, onError, strQuery) {

//here i want to call phonegap plugin and pass it post data to make server post request

}


function getJsonDataCallBack(data) 
{
//here i want to get the json data back from phonegap plugin and parse it
}
var data = { name: "getJsonData", type: "2f" };
var url = "https://api.somewebsite.com/androidMobile.aspx";

cordovaHTTP.post(url, data, { },
  function(response) {
    // success
    console.log("HTTP response: "+ response.status);
    console.log(response.data);
    // parse JSON response
    var jsonResponseObj = JSON.parse(response.data);
  }, function(response) {
    // error
    console.log("HTTP response: "+ response.status);
  }
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM