Skills Skills - 2 months ago 7
JSON Question

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

i am trying to to make a post connection with some parameters, and i will like to attach a token i stored on shared preference and attach it as an authorization header, im a new be, please find below my code

JSON parser Class

public class JSONParser {

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;

}


MainActivity Class

class MainActivity extends 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;


//Fetching token from shared preferences
SharedPreferences sharedPreferences = getSharedPreferences(Config.SHARED_PREF_NAME, Context.MODE_PRIVATE);
String token = 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;

}


The question is how do i attach the token as an authorization header while making the post connection ? thanks in advance

Answer

Hey add below line of code for that

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

Hope it will help you.