Skip to content Skip to sidebar Skip to footer

From Android I Want To Call Api With Post Method

I am getting response from API when I submit request from Postman like shown in the image screenshot1.jpg = The data I need to pass screenshot2.jpg = The result we get I tried ca

Solution 1:

You can use below method:

public String executePost(String targetURL,String urlParameters) {
    int timeout=5000;
    URL url;
    HttpURLConnectionconnection=null;
    try {
        // Create connection

        url = newURL(targetURL);
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type",
                "application/json");

        connection.setRequestProperty("Content-Length",
                "" + Integer.toString(urlParameters.getBytes().length));
        connection.setRequestProperty("Content-Language", "en-US");

        connection.setUseCaches(false);
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setConnectTimeout(timeout);
        connection.setReadTimeout(timeout);

        // Send requestDataOutputStreamwr=newDataOutputStream(
                connection.getOutputStream());
        wr.writeBytes(urlParameters);
        wr.flush();
        wr.close();

        // Get ResponseInputStreamis= connection.getInputStream();
        BufferedReaderrd=newBufferedReader(newInputStreamReader(is));
        String line;
        StringBufferresponse=newStringBuffer();
        while ((line = rd.readLine()) != null) {
            response.append(line);
            response.append('\r');
        }
        rd.close();
        return response.toString();

    } catch (SocketTimeoutException ex) {
        ex.printStackTrace();

    } catch (MalformedURLException ex) {
        Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
    } catch (UnknownHostException e) {
        e.printStackTrace();
    } catch (IOException ex) {

        Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {

        if (connection != null) {
            connection.disconnect();
        }
    }
    returnnull;
}

You can create URL parameters like:

JSONObject loginParams = newJSONObject();
loginParams .put("username", userName);
loginParams .put("password", password);
loginParams .put("platform", "ANDROID");
loginParams .put("location", "56.1603092,10.2177147");

Calling method like:

executePost(serviceURL,loginParams.toString());

Solution 2:

You can use retrofit library for easier to implement network communication with REST Service.

By the way, you can try my solution for your problem:

  • First, create an executeHttp method

    private JSONObject executeHttp(HttpUriRequest request, Context context)throws ClientProtocolException, IOException {
            HttpParamshttpParameters=newBasicHttpParams();
                // Set the timeout in milliseconds until a connection is established.// The default value is zero, that means the timeout is not used.inttimeoutConnection=3000;
                HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
                // Set the default socket timeout (SO_TIMEOUT)// in milliseconds which is the timeout for waiting for data.inttimeoutSocket=10000;
                HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
    
                DefaultHttpClientclient=newDefaultHttpClient(httpParameters);
                // add your header in here - I saw your header has 7 params
                request.addHeader("Authorization", getToken());
                request.addHeader("APIKey", API_KEY);
                request.addHeader("Content-Type", "application/x-www-form-urlencoded");
                request.addHeader("X-Request-Mime-Type", "application/json;");
                HttpResponseexecute= client.execute(request);
                InputStreamcontent= execute.getEntity().getContent();
                // implement your handle response here, below is just an exampletry {
                     returnnewJSONObject().put("content", this.convertStreamToByteArray(content));
                } catch (JSONException e) {
                //Crashlytics.logException(e);
                     Log.e(LOG_TAG, "Error converting stream to byte array: " + e.getMessage());
                     returnnewJSONObject();
    
                }
            }
    

Then create a method to handle POST request

public JSONObject doPost(List<NameValuePair> headerParams, List<NameValuePair> parameters, String url, Context context)throws ClientProtocolException, IOException {
        HttpPosthttpPost=newHttpPost(url);
        // add the header if neededif (headerParams != null) {
            for (NameValuePair headerParam: headerParams) {
                httpPost.addHeader(headerParam.getName(), headerParam.getValue());
            }
        }
        httpPost.setEntity(newUrlEncodedFormEntity(parameters, "UTF-8"));

        return executeHttp(httpPost, context);
    }

Finally, call the api just created.

JSONObject json = doPost(header, nameValuePairs, yourUrl, context);

with nameValuePairs is created by

            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            nameValuePairs.add(new BasicNameValuePair("username", userName));
            nameValuePairs.add(new BasicNameValuePair("password", password));
            nameValuePairs.add(new BasicNameValuePair("platform", "ANDROID"));
            nameValuePairs.add(new BasicNameValuePair("location", "56.1603092,10.2177147"));

Solution 3:

Issue was using the stringbuffer class, I used string to get response and it worked perfectly. Thank you every one for comments and answers.

Post a Comment for "From Android I Want To Call Api With Post Method"