针对Android的经过身份验证的POST / GET请求

时间:2014-08-26 17:17:39

标签: java android http post get

我一般都是http请求的新手,但我认为我现在已经掌握了Java,至少对于未经身份验证的请求。

我想知道如何在给定正确的api URL,授权令牌和user_id(这是我的参数)的情况下形成GET请求。我假设这是基本的http身份验证,但似乎需要用户名和密码。后端开发人员告诉我,我只需要令牌和用户ID。

我已经看到很多标题的创建示例,但没有一个对我有用,因为我不完全理解标题的内容必须是什么。任何帮助都非常感谢。

3 个答案:

答案 0 :(得分:0)

创建AsyncHttpClient并在onSuccess()中,请求所需的关键值

答案 1 :(得分:0)

创建一个Asynctask类

public class SendRequest extends AsyncTask<Void, Void, Void> {

private Context context;
private String url;
private String token;
private String uid;

public SendRequest(Context context, String token, String uid) {
    // TODO Auto-generated constructor stub
    this.context = context;
    this.token = token;
    this.uid = uid;
    url = "http://" + context.getResources().getString(R.string.url)
            + "/xyz.php";
}

@Override
protected Void doInBackground(Void... arg0) {
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("token", token));
    params.add(new BasicNameValuePair("user_id", uid));
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(url);
    try {
        httppost.setEntity(new UrlEncodedFormEntity(params));
        HttpResponse response = httpclient.execute(httppost);
    }

    catch (ClientProtocolException e) {
        Log.e("e", "error1");
        e.printStackTrace();
    } catch (IOException e) {
        Log.e("e", "error2");
        e.printStackTrace();
    }
    return null;
}

@Override
protected void onPostExecute(Void result) {
    //after http request
}
}

在你的活动中称之为

new SendRequest(par1, par2, par3).execute();

答案 2 :(得分:0)

对于GET,您可以使用下面给出的代码示例,我从服务器返回JSON响应。为了执行POST请求,将需要一些额外的安全头/令牌等以及请求数据。

class FlickrDownloader extends AsyncTask<Void, Void, Void> {



        @Override
        protected Void doInBackground(Void... params) {
            FlickrGetter getter = new FlickrGetter();

            ArrayList<FlickrItem> newItems = getter.fetchItems();

            // clear the existing array
            //items.clear();

            // add the new items to the array
            //items.addAll(newItems);

            // is this correct ? - Wrong rebuilding the list view and should not be done in background
            //adapter.notifyDataSetChanged();

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);

            //adapter.notifyDataSetChanged();
        }

    }

    public class FlickrGetter {
        public static final String TAG = "FlickrGetter";

        private static final String ENDPOINT = "https://api.flickr.com/services/rest/";
        private static final String API_KEY = "Please specify your key";
        private static final String METHOD_GET_RECENT = "flickr.photos.getRecent";
        private static final String METHOD_GET_SEARCH = "flickr.photos.search";
        private static final String PARAM_EXTRAS = "extras";

        private static final String EXTRA_SMALL_URL = "url_s";

        private static final String XML_PHOTO = "photo";

        public byte[] getUrlBytes(String urlSpec) throws IOException {
            URL url = new URL(urlSpec);
            HttpURLConnection connection = (HttpURLConnection)url.openConnection();

            try {
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                InputStream in = connection.getInputStream();

                if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
                    return null;
                }

                int bytesRead = 0;
                byte[] buffer = new byte[1024];
                while ((bytesRead = in.read(buffer)) > 0) {
                    out.write(buffer, 0, bytesRead);
                }
                out.close();
                return out.toByteArray();
            } finally {
                connection.disconnect();
            }
        }

        String getUrl(String urlSpec) throws IOException {
            return new String(getUrlBytes(urlSpec));
        }

        public ArrayList<FlickrItem> fetchItems() {
            ArrayList<FlickrItem> items = new ArrayList<FlickrItem>();

            try {
                String url = Uri.parse(ENDPOINT).buildUpon()
                        .appendQueryParameter("method", METHOD_GET_SEARCH)
                        .appendQueryParameter("api_key", API_KEY)
                        .appendQueryParameter(PARAM_EXTRAS, EXTRA_SMALL_URL)
                        .appendQueryParameter("format", "json")
                        .appendQueryParameter("text", "India")
                        .build().toString();
                Log.i("FlickrFetchr", url);
                String jsonString = getUrl(url);
                String json = jsonString.substring(14, jsonString.toString().length()-1);
                Log.i(TAG, "Received json: " + json);

                JSONObject mainObject = new JSONObject(json);
                JSONObject photoObject = mainObject.getJSONObject("photos");
                JSONArray photos = photoObject.getJSONArray("photo");
                for(int i = 0; i < photos.length(); ++i) {
                        JSONObject obj = photos.getJSONObject(i);
                        FlickrItem item = new FlickrItem();
                        item.title = obj.getString("title");
                        item.id = obj.getString("id");
                        item.url = obj.getString("url_s");
                        if(item.url != null) {
                            items.add(item);
                            Log.i(TAG, item.toString());

                        }


                }

            } catch (IOException ioe) {
                Log.e(TAG, "Failed to Get items", ioe);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return items;
        }


    }