Sign in | Sign up

V2.0 Natural

Tagged:

Currently contains 4 posts

Avatar

13 Feb, 2017 06:25AM

imanpakii

Hello
I’m trying to develop an app which use v2.0 language natural to show some result.
I already used V1.0 with get method on my app and it working fine but since I’m new at android developing I really don’t know how can I use post with passing header and body.
any source code or tutorial website on this subject would be appreciated.

Thank you
Iman

Avatar

25 Feb, 2017 04:56PM

imanpakii

I didn’t get any answer and I finally find it myself.
This is the answer:
URL url = new URL; //Enter URL here
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setDoOutput(true);
httpURLConnection.setReadTimeout(10000 /milliseconds/);
httpURLConnection.setConnectTimeout(15000 /* milliseconds */);
httpURLConnection.setRequestMethod(“POST”); // here you are telling that it is a POST request, which can be changed into “PUT”, “GET”, “DELETE” etc.
httpURLConnection.setRequestProperty(“Content-Type”, “application/json”); // here you are setting the `Content-Type` for the data you are sending which is `application/json`
httpURLConnection.setRequestProperty(“x-app-id”, “YOUR ID”);
httpURLConnection.setRequestProperty(“x-app-key”, “YOUR APP KEY”);
httpURLConnection.connect();

JSONObject jsonObject = new JSONObject(); jsonObject.put(“query”, params0 + " lbs of "+params1); DataOutputStream wr = new DataOutputStream(httpURLConnection.getOutputStream()); wr.writeBytes(jsonObject.toString()); wr.flush(); wr.close(); String json_response = ""; InputStreamReader in = new InputStreamReader(httpURLConnection.getInputStream()); BufferedReader br = new BufferedReader(in); String text = ""; while ((text = br.readLine()) != null) { json_response += text; } JSONObject niutrition = new JSONObject(json_response); JSONArray foods = niutrition.getJSONArray(“foods”); JSONObject arryJson = foods.getJSONObject(0); calories = arryJson.getDouble(“nf_calories”); strCal = String.valueOf(calories); testStr0=“Calories=”+strCal; for(int i=1;i<10;i++){ testStr[i]= String.valueOf(i); }

Avatar

9 Mar, 2017 09:51PM

urmil025

i believe this should be pretty straightforward. Good that it works for you now.

Avatar

18 Aug, 2017 03:00PM

chrisscherer

Look into the google provided GSON and Volley libraries, they’ll make your life waaay easier. I’ve modified their GsonRequest object a bit but my calls look like this:

String requestURL = “https://trackapi.nutritionix.com/v2/natural/nutrients”; GsonRequest<RecipeRequest, RecipeResponse> request = new GsonRequest<>( Request.Method.POST, requestURL, getRecipeRequest(), RecipeResponse.class, NetworkUtils.SetupNutritionIXHeaders(), “application/json”, response → { String s = response.toString(); }, e → { String s = “Fail”; } ); RequestHandler.getInstance(this).addToRequestQueue(request);
Reply to thread