1

我是 android 新手,我做了一个活动,我必须发布一些参数来进行 api 调用并获得响应,我必须传递一些附加到请求 url 和其他 Json 格式的参数,请告诉我我该怎么做做,我的示例网址请求如下:

http://dev.abctest.com/api/v1/book?customer_firstname=jigar&customer_lastname=jims&customer_mobile=9033309333&customer_email=jigar@epagestore.com&source_country=India&number_of_travellers=15

以及 json 正文中的其他参数,如下所示:

{

    "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"
        }
    ]
}
4

2 回答 2

2
  1. 将 JsonParserHelper 用作实用程序类。每次点击网址时。

a.) 上课并在该课程上分隔您的网址让假设 App_WebServiceUrls

public class App_WebServiceUrls {

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

}

2.现在调用webservice/Web Api时。在单独的线程中进行 api 调用或使用 Asynctasks 来避免 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();

/用于进行 webapi 调用的辅助类/

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;

    }

}
于 2014-08-04T12:01:25.477 回答
1

首先,您需要将 url 字段附加到您的基本 url。然后,您可以添加可选字段(如果有)。然后将您的数据作为 HttpPost 中的实体,其中 url 将是处理后获得的。

尝试以下:

  1. 要调用的父方法。

    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. 它将 url 参数附加到基本 url

    private String getUrlPathForGet(List<NameValuePair> urlFields) {
    
    String path = "";
    
    if (urlFields != null) {
    
        for (NameValuePair pair : urlFields) {
        path = path + "/" + pair.getValue();
        }
    }
    
    return path;
    }
    
  3. 使用修改后的 url 将表单数据作为实体添加到 HttpPost 对象。

    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
    }
    }
    
于 2014-08-04T11:56:13.013 回答