如何在 android 上 post 授权 header,令牌存储在共享首选项中

how to post authorization header on android, token is stored on shared preference

我正在尝试与某些参数建立 post 连接,我想附加一个存储在共享首选项中的令牌并将其作为授权附加 header,我是一个新的是,请在下面找到我的代码

JSON 解析器 Class

public class JSON解析器{

static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
static int  statusCode ;
// constructor
public JSONParser() {

}
public int getStatusCode(){
    return statusCode;
}




// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
        List<NameValuePair> params) {



    // Making HTTP request
    try {

        // check for request method
        if(method == "POST"){


            // request method is POST
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params));

            HttpResponse httpResponse = httpClient.execute(httpPost);

            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();
            statusCode = httpResponse.getStatusLine().getStatusCode();


        }else if(method == "GET"){
            // request method is GET
            DefaultHttpClient httpClient = new DefaultHttpClient();
            String paramString = URLEncodedUtils.format(params, "utf-8");
            url += "?" + paramString;
            HttpGet httpGet = new HttpGet(url);

            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();
            statusCode = httpResponse.getStatusLine().getStatusCode();
        }           

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

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is, HTTP.UTF_8), 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 {
        jObj = new JSONObject(json.substring(json.indexOf("{"), json.lastIndexOf("}") + 1));
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data [" + e.getMessage()+"] "+json);
    }

    // return JSON String
    return jObj;

}

主要活动Class

class MainActivity 扩展了 AsyncTask {

    final  String email = editTextEmail.getText().toString();
    final  String name = editUser_name.getText().toString();
    final  String phone = mPhoneEdit.getText().toString();
    String image = getStringImage(bitmap);
    final  String gen = gender;
    final  String dob = dateOfBirth.getText().toString();
    final  String industry = in;
    final  String school = sc;

//从共享首选项中获取令牌 SharedPreferences sharedPreferences = getSharedPreferences(Config.SHARED_PREF_NAME, Context.MODE_PRIVATE); 字符串标记 = sharedPreferences.getString(Config.TOKEN_SHARED_PREF, "");

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(MainActivity .this);
        pDialog.setMessage("Loading..Please wait");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    }


    protected String doInBackground(String... args) {

        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();

        params.add(new BasicNameValuePair(Config.KEY_EMAIL, email));
        params.add(new BasicNameValuePair(Config.KEY_NAME,name));
        params.add(new BasicNameValuePair(Config.KEY_PHONE, phone));
        params.add(new BasicNameValuePair(Config.KEY_FBPHOTO, image));
        params.add(new BasicNameValuePair(Config.KEY_FBGENDER, gen));
        params.add(new BasicNameValuePair(Config.KEY_FBDOB, dob));
        params.add(new BasicNameValuePair(Config.KEY_SCHOOL, school));
        params.add(new BasicNameValuePair(Config.KEY_INDUSTRY, industry));



        JSONObject json = jsonParser.makeHttpRequest(URL_USERUPDATEPROFILE,"POST", params);

       Log.d(" response", json.toString());
        Config.statusCode = jsonParser.getStatusCode();

        return null;

    }

问题是如何在建立 post 连接时附加令牌作为授权 header?提前致谢

嘿,为此添加下面的代码行

String accessToken = "Bearer " + MyPreference.getString(context, "access_token");
httppost.setHeader("Authorization", "Bearer "+accessToken);

希望对您有所帮助。