【问题标题】:Android Http Handler set TokenAndroid Http Handler 设置 Token
【发布时间】:2016-10-20 09:03:18
【问题描述】:

在我的应用程序中,我使用 Http Handler 检索 json 数据并将其解析为列表,一切正常。 现在我必须加载一个需要令牌的seconod json。 我已经通过 http post 请求生成了这个令牌,但是现在我不知道如何在我的异步任务中设置这个令牌 我该怎么做,这是我调用 json 的代码:

private class GetUber extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // Showing progress dialog
        pDialog = new ProgressDialog(Tariffe.this);
        pDialog.setMessage("Cacolo tariffa ...");
        pDialog.setCancelable(false);
        pDialog.show();

    }

    @Override
    protected Void doInBackground(Void... arg0) {
        HttpHandler sh = new HttpHandler();

        // Making a request to url and getting response
        String jsonStr = sh.makeServiceCall(SERVICE_UBER);

        Log.e(TAG, "Response from url: " + jsonStr);

        if (jsonStr != null) {
            try {
                JSONObject jsonObj = new JSONObject(jsonStr);

                // Getting JSON Array node
                JSONArray contacts = jsonObj.getJSONArray("prices");

                // looping through All Contacts
                for (int i = 0; i < contacts.length(); i++) {
                    JSONObject c = contacts.getJSONObject(i);

                    //String id = c.getString("id");
                    String name = c.getString("display_name");
                    String costo = c.getString("estimate");

                    // Phone node is JSON Object
                    //JSONObject phone = c.getJSONObject("phone");
                   //String tipo = phone.getString("display_name");
                    //String costo = phone.getString("estimate");

                    // tmp hash map for single contact
                    HashMap<String, String> contact = new HashMap<>();

                    // adding each child node to HashMap key => value
                    //contact.put("id", id);
                    contact.put("name", name);
                    contact.put("costo", costo);

                    // adding contact to contact list
                    uberList.add(contact);
                }
            } catch (final JSONException e) {
                Log.e(TAG, "Json parsing error: " + e.getMessage());
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(),
                                "Json parsing error: " + e.getMessage(),
                                Toast.LENGTH_LONG)
                                .show();
                    }
                });

            }
        } else {
            Log.e(TAG, "Couldn't get json from server.");
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(getApplicationContext(),
                            "Couldn't get json from server. Check LogCat for possible errors!",
                            Toast.LENGTH_LONG)
                            .show();
                }
            });

        }

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        // Dismiss the progress dialog
        if (pDialog.isShowing())
            pDialog.dismiss();
        /**
         * Updating parsed JSON data into ListView
         * */
        ListAdapter adapter = new SimpleAdapter(
                Tariffe.this, uberList,
                R.layout.raw_tariffe, new String[]{"name", "costo"}, new int[]{R.id.tipo, R.id.costo});

        lv.setAdapter(adapter);
    }

}

谢谢

【问题讨论】:

  • 我相信你从这里得到了一些代码示例:androidhive.info/2012/01/android-json-parsing-tutorial 如果是这种情况,你将不得不调整HttpHandler 来进行 POST,或者自己使用HttpURLConnection
  • 是的,我看过 AndroidHive 写的代码
  • 哦,我看错了,你已经做了 POST。请说明您需要做的HTTP请求的顺序,以及是否可以同时执行
  • 我做了一个 POST 并且我收到了一个令牌。现在我想将此令牌添加到我之前的代码描述中,但我不知道如何
  • 您可以将令牌存储在当前的Activity 中,并从那里继续您的应用程序进度。我认为这更像是您的应用架构的问题

标签: android json token httphandler


【解决方案1】:
public class HttpHandler {

    private static final String TAG = HttpHandler.class.getSimpleName();

    public HttpHandler() {
    }

    public String makeServiceCall(String reqUrl) {
        String response = null;
        try {
            URL url = new URL(reqUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            // read the response
            InputStream in = new BufferedInputStream(conn.getInputStream());
            response = convertStreamToString(in);
        } catch (MalformedURLException e) {
            Log.e(TAG, "MalformedURLException: " + e.getMessage());
        } catch (ProtocolException e) {
            Log.e(TAG, "ProtocolException: " + e.getMessage());
        } catch (IOException e) {
            Log.e(TAG, "IOException: " + e.getMessage());
        } catch (Exception e) {
            Log.e(TAG, "Exception: " + e.getMessage());
        }
        return response;
    }

    private String convertStreamToString(InputStream is) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line).append('\n');
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }
}

【讨论】:

  • 您需要在代码中添加解释,这样答案才会有帮助。
【解决方案2】:

要在HttpHandler 类发出的请求中添加标头字段,您需要对其进行修改。你可以添加这个:

public class HttpHandler {

    // ...

    public String makeServiceCall(String reqUrl, String token) {

        // ...

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("token", token);

        // ...
    }
}

顺便说一句,HttpHandler 只是HttpURLConnection Java 类的包装器,而且这个包装器是有限的和有限制的。我建议您制作自己的包装器。

【讨论】:

    【解决方案3】:

    添加如下标题

                HashMap<String, String> headers = Constant
                        .getHeaderParameter(cntx);
                for (Map.Entry<String, String> e : headers.entrySet()) {
                    httpPost.setHeader(e.getKey(), e.getValue());
                }
    
                httpPost.setEntity(entity);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-18
      • 2023-03-31
      • 2011-11-22
      • 1970-01-01
      • 2015-05-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多