user3820044
user3820044

Reputation: 177

How to pass half parameters in requestUrl and other in JSON request in android?

I am new to android,I have made an activity in that i have to post some parameters to make api call and get response,I have to pass some parameters appending to request url and others as in Json format,Please tell me how can i do,My sample url request is as below:

http://dev.abctest.com/api/v1/book?customer_firstname=jigar&customer_lastname=jims&customer_mobile=9033309333&[email protected]&source_country=India&number_of_travellers=15

and other parameters in json body like below:

{

    "destinations": [
        {
            "city_id": 1,
            "start_date": "2014/08/28",
            "end_date": "2014/09/30"
        },
        {
            "city_id": 5,
            "start_date": "2014/08/10",
            "end_date": "2014/09/03"
        }
    ]
}

Upvotes: 1

Views: 1000

Answers (2)

DeepakPanwar
DeepakPanwar

Reputation: 1389

  1. Make use of JsonParserHelper as a Utility class. Every time when you hit url.

a.) Take a class and seperate your urls on that class Let Suppose App_WebServiceUrls

public class App_WebServiceUrls {

public static String GetDetails ="http://dev.abctest.com/api/v1/book";

}

2.Now when making call to webservice/Web Api. Make api call in seperate thred or use Asynctasks So to avoit NetworkOnMainThredException.

new Thread(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub

                // Add your data
            List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();

                nameValuePair.add(new BasicNameValuePair(customer_firstname, "Deepak"));
                nameValuePair.add(new BasicNameValuePair(customer_lastname, "Panwar"));


JSONObject json = null;

        try {

            json = new JSONObject();

    json = JsonParserHelper.makeHttpRequest(
                    App_WebServiceUrls.CompanyDivisions, "GET", nameValuePair);

            Log.d("Division List Response:", "" + json);

            if (json != null) {
}else
{

    /**To print tost on ui thread**/
    runOnUiThread(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub

              /**Write Toast here**/

            }
        });

} catch (JSONException e) {
            e.printStackTrace();
        }


            }
        }).start();

/helper class for making webapi calls/

public class JsonParserHelper {

    static InputStream is = null;

    static JSONObject jObj = null;

    static JSONArray jArr = null;

    static String json = "";

    public static JSONObject makeHttpRequest(String url, String method,

    List<NameValuePair> params) {

        try {

            if (method == "POST") {

                DefaultHttpClient httpClient = new DefaultHttpClient();

                String paramString = URLEncodedUtils.format(params, "utf-8");
                url += "?" + paramString;

                Log.v("Urltocheck", "" + url);

                HttpPost httpPost = new HttpPost(url);
                httpPost.setEntity(new UrlEncodedFormEntity(params, "utf-8"));
                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();

                is = httpEntity.getContent();

            } else if (method == "GET") {
                // request method is GET
                DefaultHttpClient httpClient = new DefaultHttpClient();

                String paramString = URLEncodedUtils.format(params, "utf-8");
                url += "?" + paramString;

                Log.v("Urltocheck", "" + url);

                HttpGet httpGet = new HttpGet(url);
                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
            }

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            // jArr = new JSONArray(json);

            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String (Array)
        // return jArr;

        return jObj;

    }

}

Upvotes: 2

Ritesh Gune
Ritesh Gune

Reputation: 16739

First you need to append the url fields to your base url. Then you can add the optional fields if you have any. Then the your data as an entity in HttpPost where the url will be the one obtained after processing.

Try following :

  1. The parent method to be called.

    public void request(String baseUrl,List<NameValuePair> urlFields, List<NameValuePair> formData,List<NameValuePair> optionalData ){
    
    // Append params to the URL 
    if (urlFields != null)
        baseUrl = baseUrl + getUrlPathForGet(urlFields);
    
    // adds Optional fields to the Url
    if (optional != null)
        baseUrl = baseUrl + "?" + URLEncodedUtils.format(optionalData, "utf-8");
    
    postData(baseUrl,formData);
    
    }
    
  2. It will append the url params to the base url

    private String getUrlPathForGet(List<NameValuePair> urlFields) {
    
    String path = "";
    
    if (urlFields != null) {
    
        for (NameValuePair pair : urlFields) {
        path = path + "/" + pair.getValue();
        }
    }
    
    return path;
    }
    
  3. Add the form data as entity to HttpPost object with the modified url.

    public void postData(String baseUrl,List<NameValuePair> formData) {
    
    // Create a new HttpClient and Post Header
    HttpClient httpclient = new DefaultHttpClient();
    // pass the url as parameter and create HttpPost object.
    HttpPost post = new HttpPost(baseUrl);
    
    // Add header information for your request - no need to create 
    // BasicNameValuePair() and Arraylist.
    post.setHeader("Authorization", "Bearer " + token);
    post.setHeader("Content-Type", "application/json");
    post.setHeader("Cache-Control", "no-cache");    
    
    try {       
    
    // pass the content as follows:
    post.setEntity(new UrlEncodedFormEntity(formData,
                        HTTP.UTF_8));
    
    // Execute HTTP Post Request
    HttpResponse response = httpclient.execute(post);
    
    // TODO: Process your response as you would like.
    
    } catch (IOException e) {
        // TODO Auto-generated catch block
    }
    }
    

Upvotes: 1

Related Questions