How to implement C2DM in android? - android

I am searching about how to send notification using C2DM. I found something and using that I am able to generate Registration Key as well as an Authentication Key.
But after that in ServerSimulator class (sever side code) I got 401 Error (401 Unauthorized).Now I passed Username and Password manually, which I synchronized in my Android device. I get same error as before.
I face this problem when I click on send message button..
I am stuck on this query. Has anyone managed to do this?
public class ServerSimulator extends Activity
{
private SharedPreferences prefManager;
private final static String AUTH = "authentication";
private static final String UPDATE_CLIENT_AUTH = "Update-Client-Auth";
public static final String PARAM_REGISTRATION_ID = "registration_id";
public static final String PARAM_DELAY_WHILE_IDLE = "delay_while_idle";
public static final String PARAM_COLLAPSE_KEY = "collapse_key";
private static final String UTF8 = "UTF-8";
// Registration is currently hardcoded
private final static String YOUR_REGISTRATION_STRING = "APA91bFkxmtIj5XiBU-Cze64s0gXNb7OmiWWZg-qLKibpLsVXaWq1X7hoRV9Ld9COYXirZAgkYegZBdBfUGt3lgtuhNJopvHB0KJ5ZyJ6Kt_HYRrZhgdJ1Y";
private SharedPreferences prefs;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
prefManager = PreferenceManager.getDefaultSharedPreferences(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.mymenu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menuitem_user:
Intent intent = new Intent(this, UserPreferences.class);
startActivity(intent);
break;
default:
break;
}
return false;
}
public void getAuthentification(View view) {
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(this);
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(
"https://www.google.com/accounts/ClientLogin");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("Email","myEmail id")));
nameValuePairs.add(new BasicNameValuePair("Passwd","my password")));
nameValuePairs.add(new BasicNameValuePair("accountType", "GOOGLE"));
nameValuePairs.add(new BasicNameValuePair("source","Google-cURL-Example"));
nameValuePairs.add(new BasicNameValuePair("service", "ac2dm"));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = client.execute(post);
BufferedReader rd = new BufferedReader(new InputStreamReader(
response.getEntity().getContent()));
String line = "";
while ((line = rd.readLine()) != null) {
Log.e("HttpResponse", line);
if (line.startsWith("Auth=")) {
Editor edit = prefManager.edit();
edit.putString(AUTH, line.substring(5));
edit.commit();
String s = prefManager.getString(AUTH, "n/a");
Toast.makeText(this, s, Toast.LENGTH_LONG).show();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void showAuthentification(View view) {
String s = prefManager.getString(AUTH, "n/a");
Toast.makeText(this, s, Toast.LENGTH_LONG).show();
}
public void sendMessage(View view) {
try {
Log.e("Tag", "Started");
String auth_key = prefManager.getString(AUTH, "n/a");
// Send a sync message to this Android device.
StringBuilder postDataBuilder = new StringBuilder();
postDataBuilder.append(PARAM_REGISTRATION_ID).append("=")
.append(YOUR_REGISTRATION_STRING);
// if (delayWhileIdle) {
// postDataBuilder.append("&").append(PARAM_DELAY_WHILE_IDLE)
// .append("=1");
// }
postDataBuilder.append("&").append(PARAM_COLLAPSE_KEY).append("=")
.append("0");
postDataBuilder.append("&").append("data.payload").append("=")
.append(URLEncoder.encode("Lars war hier", UTF8));
byte[] postData = postDataBuilder.toString().getBytes(UTF8);
// Hit the dm URL.
URL url = new URL("https://android.clients.google.com/c2dm/send");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded;charset=UTF-8");
conn.setRequestProperty("Content-Length",
Integer.toString(postData.length));
conn.setRequestProperty("Authorization", "GoogleLogin auth="
+ auth_key);
OutputStream out = conn.getOutputStream();
out.write(postData);
out.close();
int responseCode = conn.getResponseCode();
Log.e("Tag", String.valueOf(responseCode));
// Validate the response code
if (responseCode == 401 || responseCode == 403) {
// The token is too old - return false to retry later, will
// fetch the token
// from DB. This happens if the password is changed or token
// expires. Either admin
// is updating the token, or Update-Client-Auth was received by
// another server,
// and next retry will get the good one from database.
Log.e("C2DM", "Unauthorized - need token");
}
// Check for updated token header
String updatedAuthToken = conn.getHeaderField(UPDATE_CLIENT_AUTH);
if (updatedAuthToken != null && !auth_key.equals(updatedAuthToken)) {
Log.i("C2DM",
"Got updated auth token from datamessaging servers: "
+ updatedAuthToken);
Editor edit = prefManager.edit();
edit.putString(AUTH, updatedAuthToken);
}
String responseLine = new BufferedReader(new InputStreamReader(
conn.getInputStream())).readLine();
// NOTE: You *MUST* use exponential backoff if you receive a 503
// response code.
// Since App Engine's task queue mechanism automatically does this
// for tasks that
// return non-success error codes, this is not explicitly
// implemented here.
// If we weren't using App Engine, we'd need to manually implement
// this.
if (responseLine == null || responseLine.equals("")) {
Log.i("C2DM", "Got " + responseCode
+ " response from Google AC2DM endpoint.");
throw new IOException(
"Got empty response from Google AC2DM endpoint.");
}
String[] responseParts = responseLine.split("=", 2);
if (responseParts.length != 2) {
Log.e("C2DM", "Invalid message from google: " + responseCode
+ " " + responseLine);
throw new IOException("Invalid response from Google "
+ responseCode + " " + responseLine);
}
if (responseParts[0].equals("id")) {
Log.i("Tag", "Successfully sent data message to device: "
+ responseLine);
}
if (responseParts[0].equals("Error")) {
String err = responseParts[1];
Log.w("C2DM",
"Got error response from Google datamessaging endpoint: "
+ err);
// No retry.
throw new IOException(err);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}

You are currently implementing C2DM in an older way. The way you are doing offers a lot of customizability, but not many people need that kind of customizability. With the new Google Plugin 2.4 Beta they have actually started integrating it all in, and it's pretty nice.
I'd highly recommend you watch the Google IO Android + AppEngine. They show how to integrate Android, AppEngine, and C2DM together really really simply. You can create something they call an "AppEngine Connected Android Project". So instead of making a ServerSimulator, you'd be actually working with a real server that can all be setup for free.
http://www.youtube.com/watch?v=M7SxNNC429U
If you wanted to move to another server, you'd have to re-write the server-side code, and then just change the URL that it's posting to. Pretty simple. I'd highly recommend checking out this example and working with the stock code, as it gives you something working right off the bat to play with:
FYI, there is currently a bug in the code (as it is in beta atm) when it comes to registering to a real hosted appengine server (everything works fine locally). It tries to send an expired registration token. I've been in contact with the google developers and they provided a fix for me. Let me know if you get to the point where you need it.

Related

How to perform network operation in AsyncTask - Android

I am new to Android and I am using the a button click to send a push notification using GCM. I have the function to perform the GCM push. I need it to be converted from the function to a AsyncTask class. I saw a lot from the internet and still facing trouble. Can anyone help me to convert it ?
The push function
public void sendPush(int position){
pushProgressBar.setVisibility = (View.VISIBLE)
try {
// Prepare JSON containing the GCM message content. What to send and where to send.
JSONObject jGcmData = new JSONObject();
JSONObject jData = new JSONObject();
jData.put("message", "Hello");
// Where to send GCM message.
TinyDB tinyDB = new TinyDB(mContext);
ArrayList<String> userToken = tinyDB.getListString("tokenList");
String tokenToSend = userToken.get(position);
jGcmData.put("to", tokenToSend);
// What to send in GCM message.
jGcmData.put("data", jData);
// Create connection to send GCM Message request.
URL url = new URL("https://android.googleapis.com/gcm/send");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Authorization", "key=" + R.string.apikey);
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestMethod("POST");
conn.setDoOutput(true);
// Send GCM message content.
OutputStream outputStream = conn.getOutputStream();
outputStream.write(jGcmData.toString().getBytes());
// Read GCM response.
InputStream inputStream = conn.getInputStream();
String resp = IOUtils.toString(inputStream);
System.out.println(resp);
System.out.println("Check your device/emulator for notification or logcat for " +
"confirmation of the receipt of the GCM message.");
pushProgressBar.setVisibility = (View.GONE)
} catch (IOException e) {
System.out.println("Unable to send GCM message.");
System.out.println("Please ensure that API_KEY has been replaced by the server " +
"API key, and that the device's registration token is correct (if specified).");
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
Thanks in advance. Hope I learn from this.
Example basic AsyncTask:
class PushTask extends AsyncTask<Integer, Integer, Integer> {
#Override
protected void onPreExecute() {
pushProgressBar.setVisibility = (View.VISIBLE);
}
#Override
protected Integer doInBackground(Integer... position) {
int post = position[0];
int respCode = 0;
try {
//your sending code here..
//got gcm code
respCode = 1;
} catch (IOException e) {
//json IOException
//cannot send gcm
respCode = 2;
} catch (JSONException e) {
//json Exception
respCode = 3;
}
return respCode;
}
#Override
protected void onPostExecute(Integer response) {
switch(response)
case 1:
System.out.println("Check your device/emulator for notification or logcat for " +
"confirmation of the receipt of the GCM message.");
break;
case 2:
System.out.println("Please ensure that API_KEY has been replaced by the server " +
"API key, and that the device's registration token is correct (if specified).");
break;
case 3:
//print json Exception error
break;
default:
break;
pushProgressBar.setVisibility = (View.GONE);
}
}
You can execute the class by execute
new PushTask().execute(1 or your position);
This is example only, you can modified the code according your requirement.

Using Twitter Fabric to retrieve my own account tweets

I'm currently using twitter fabric framework and trying to retrieve the list of my own account tweets. I tried searching online to no avail. The example in the document shows how to display a tweet based on tweetID. I do not want that. I do understand that REST client makes a http connection with the supplied variables and to retrieve the JSON results back to parse and etc.
This are my current codes which upon successful login it will display another activity which i want my tweets to be shown here.
public void success(Result<TwitterSession> result) {
// Do something with result, which provides a TwitterSession for making API calls
TwitterSession session = Twitter.getSessionManager().getActiveSession();
TwitterAuthToken authToken = session.getAuthToken();
token = authToken.token;
secret = authToken.secret;
Log.i("token",token);
Log.i("secret",secret);
successNewPage();
}
I have also passed the token and secret key over to the next activity using intent
public void successNewPage(){
Intent intent = new Intent(this, LoginSuccess.class);
intent.putExtra("token",token);
intent.putExtra("secret", secret);
startActivity(intent);
}
On the new activity class, i followed their documentation and came out with this,
TwitterAuthConfig authConfig = new TwitterAuthConfig("consumerKey", "consumerSecret");
Fabric.with(this, new TwitterCore(authConfig), new TweetUi());
TwitterCore.getInstance().logInGuest(new Callback() {
public void success(Result appSessionResult) {
//Do the rest API HERE
Bundle extras = getIntent().getExtras();
String bearerToken = extras.getString("token");
try {
fetchTimelineTweet(bearerToken);
} catch (IOException e) {
e.printStackTrace();
}
}
public void failure(TwitterException e) {
Toast.makeText(getApplicationContext(), "Failure =)",
Toast.LENGTH_LONG).show();
}
});
}
And the retrieve of tweets would be:
// Fetches the first tweet from a given user's timeline
private static String fetchTimelineTweet(String endPointUrl)
throws IOException {
HttpsURLConnection connection = null;
try {
URL url = new URL(endPointUrl);
connection = (HttpsURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("GET");
connection.setRequestProperty("Host", "api.twitter.com");
connection.setRequestProperty("User-Agent", "anyApplication");
connection.setRequestProperty("Authorization", "Bearer " + endPointUrl);
connection.setUseCaches(false);
String res = readResponse(connection);
Log.i("Response", res);
return new String();
} catch (MalformedURLException e) {
throw new IOException("Invalid endpoint URL specified.", e);
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
What i get in my log is:
380-380/com.example.john.fabric W/System.errīš• java.io.IOException: Invalid endpoint URL specified.
Is my url wrong? Or is the token which I set in the endpointURL wrong too?
Any advice would be greatly appreciated. Thanks!
That should be the case, the message was thrown by the fetchTimelineTweet function. That should be caused by this line : URL url = new URL(endPointUrl); which tells that the endPointUrl causes MalformedURLException
EDIT :
According to the Twitter Dev Page, you should put this as endpointURL : https://dev.twitter.com/rest/reference/get/statuses/user_timeline and pass the user screenname as parameter.
EDIT 2 :
I think your code should be like this :
private static String fetchTimelineTweet(String endPointUrl, String token) // this line
throws IOException {
HttpsURLConnection connection = null;
try {
URL url = new URL(endPointUrl);
connection = (HttpsURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("GET");
connection.setRequestProperty("Host", "api.twitter.com");
connection.setRequestProperty("User-Agent", "anyApplication");
connection.setRequestProperty("Authorization", "Bearer " + token); // this line
connection.setUseCaches(false);
String res = readResponse(connection);
Log.i("Response", res);
return new String();
} catch (MalformedURLException e) {
throw new IOException("Invalid endpoint URL specified.", e);
} finally {
if (connection != null) {
connection.disconnect();
}
}
}

Properly implement AccountManager, oauth-2 and expired token

I am struggling with Account manager and OAuth-2 for some time, I have already implemented AccountManager (with service and account authenticator), Login activity with webview, etc.
I implemented all oauth-2 flow, when user enters its credentials on webview, and I save access token as AccountManager password.
The last thing I do now know how correctly implement the flow when I do an http-request to server, and its responce is Json with
{"message":"access_token_is_expired","error":true....}
so I should read this responce, analize it and do another request with resresh token to get another access token.
How correctly implements this? Where? In what class?
May be my Authenticator.getAuthToken method should be improved?
this is the code:
#Override
public Bundle getAuthToken(AccountAuthenticatorResponse response, Account account,
String authTokenType, Bundle loginOptions) throws NetworkErrorException {
Log.v(TAG, "getAuthToken()");
if (!authTokenType.equals(Const.AUTHTOKEN_TYPE)) {
final Bundle result = new Bundle();
result.putString(AccountManager.KEY_ERROR_MESSAGE, "invalid authTokenType");
return result;
}
final AccountManager am = AccountManager.get(mContext);
final String auth_token = am.getPassword(account);
if (auth_token != null) {
final Bundle result = new Bundle();
result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
result.putString(AccountManager.KEY_ACCOUNT_TYPE, Const.ACCOUNT_TYPE);
result.putString(AccountManager.KEY_AUTHTOKEN, auth_token);
return result;
}
final Intent intent = new Intent(mContext, LoginActivity.class);
intent.putExtra(Const.KEY_SERVER, am.getUserData(account, Const.KEY_SERVER));
//intent.putExtra(LoginActivity.PARAM_AUTHTOKEN_TYPE, authTokenType);
intent.putExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE, response);
final Bundle bundle = new Bundle();
bundle.putParcelable(AccountManager.KEY_INTENT, intent);
return bundle;
}
#Override
protected JSONObject doInBackground(Void... params) {
InputStream is = null;
try {
String url = "...";
URL obj = new URL(url);
HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
String urlParameters = "access_token=" + mToken;
DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
conn.connect();
int response_code = conn.getResponseCode();
is = conn.getInputStream();
String str_response = NetworkUtilities.readStreamToString(is, 500);
JSONObject response = new JSONObject(str_response);
return response;
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
I did a huge work to understand this, but I failure.
After several days and because of luck of information in the Net, I read codes on github and did some researches. In order to help somebody like me:
The expired token can be reasked in getAuthToken method above, but adding in Bundle (loginOptions) information that it should be reasked from server (for example, as "forceReauth" = true )
I check this parameter inside method and ask the method (2nd peace of code above), otherwize I use usual flow.
The second important thing - one row of code, that I see in here
Why is AccountAuthenticator#getAuthToken() not called?
God bless Tom G (I cannot add him a vote, because of luck of my reputation). The line of code
with invalidateAuthToken BEFORE getAuthToken did everything for me. Add him a vote for me, if you found this useful.

Trouble with setting the Nest field values via java/android code

I am writing android code to change the field in a Nest thermostat using the newly released API. Authentication and getting the field values is working just perfect, however I am haing problem with changing the field values. Based on the the API for changing the field values you need to use HTTP put, but once I am doing this, nothing happens in the device (the value (e.g. the value of target_temperature_f doesn't change!))
Here is my android code:
String url = "https://developer-api.nest.com/devices/thermostats/"
+ this.device_id + "?auth=" + this.access_token;
try{
HttpClient httpclient = new DefaultHttpClient();
/** set the proxy , not always needed */
HttpHost proxy = new HttpHost(proxy_ip,proxy_port);
httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,proxy);
// Set the new value
HttpPut httpPut = new HttpPut(url);
httpPut.setHeader("Content-Type", "application/json");
JSONObject jsonObj = new JSONObject("{\"target_temperature_f\":'60'}");
HttpEntity put_entity = new StringEntity(jsonObj.toString());
httpPut.setEntity(put_entity);
HttpResponse put_response = httpclient.execute(httpPut);
I can set the field in the device via "curl" command in linux though!! So the device is working fine.
Any help is highly appreciated!
I'm unsure of how to do it using the DefaultHttpClient and according to the documentation it has been deprecated in favor of HttpURLConnection.
Here's some code that uses HttpURLConnection that I've tested with Hue lights.
This will open a URL connection and perform a POST query with the given body. The readFromHttpConnection method expects a JSON response. It looks like Nest uses JSON so this may work for your needs.
private String synchronousPostMethod(String destination, String body)
{
Log.i(TAG, "Attempting HTTP POST method. Address=" + destination + "; Body=" + body);
String responseReturn;
try
{
HttpURLConnection httpConnection = openConnection(destination);
httpConnection.setDoOutput(true);
httpConnection.setRequestMethod("POST");
writeToHttpConnection(httpConnection, body);
responseReturn = readFromHttpConnection(httpConnection);
}
catch(Exception e)
{
responseReturn = RESPONSE_FAIL_MESSAGE + "; exception = " + e;
}
Log.i(TAG, "Result of HTTP POST method: " + responseReturn);
return responseReturn;
}
These are the helper methods.
private HttpURLConnection openConnection(String destination)
{
HttpURLConnection httpConnection = null;
try
{
URL connectionUrl = new URL(destination);
httpConnection = (HttpURLConnection) connectionUrl.openConnection();
}
catch(MalformedURLException malformedUrlException)
{
Log.w(TAG, "Failed to generate URL from malformed destination: " + destination);
Log.w(TAG, "MalformedURLException = " + malformedUrlException);
}
catch(IOException ioException)
{
Log.w(TAG, "Could not open HTTP connection. IOException = " + ioException);
}
return httpConnection;
}
private boolean writeToHttpConnection(HttpURLConnection httpConnection, String data)
{
// No data can be written if there is no connection or data
if(httpConnection == null || data == null)
{
return false;
}
try
{
OutputStreamWriter outputStream = new OutputStreamWriter(httpConnection.getOutputStream());
outputStream.write(data);
outputStream.close();
}
catch(IOException ioException)
{
Log.w(TAG, "Failed to get output stream from HttpUrlConnection. IOException = " + ioException);
return false;
}
return true;
}
private String readFromHttpConnection(HttpURLConnection httpConnection)
{
String responseReturn = "";
if(httpConnection != null)
{
try
{
InputStream response = httpConnection.getInputStream();
int size;
do
{
byte[] buffer = new byte[mResponseBufferSize];
size = response.read(buffer, 0, mResponseBufferSize);
// Convert the response to a string then add it to the end of the buffer
responseReturn += new String(buffer, 0, size);
}while(size < mResponseBufferSize || size <= 0);
// Cleanup
response.close();
}
catch (IOException ioException)
{
Log.w(TAG, "Failed to get input stream from HttpUrlConnection. IOException = " + ioException);
}
}
return responseReturn;
}

Your browser sent a request that this server could not understand HttpsURLConnection

I am making a login app to retreive some information from the link that appears in the code. My problem is that I'm getting a "400 Bad request. Your browser sent a request that this server could not understand. [...] Server at idp.tut.fi Port 443" in the Log file.
Besides, that link handles RC4_128 with SHA1 for authentication and RSA for key exchange but don't really know where I can apply those protocols in my code.
Thanks for your help!
This is my code:
public class POPLogin extends Activity {
private EditText usr, pass;
private Button submitButton;
private CharSequence notify;
private String res, resp;
private final String link = "https://idp.tut.fi/idp/Authn/UserPassword";
private URL url;
public static boolean isNetworkAvailable(Context context) {
return ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo() != null;
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_poplogin);
usr = ((EditText) findViewById(R.id.usernameField));
pass = ((EditText) findViewById(R.id.passwordField));
submitButton = (Button) findViewById(R.id.submitButton);
submitButton.getBackground().setColorFilter(new LightingColorFilter(0x00FFB90F, 0xFFAA0000));
/*
* This method controls the login button so that the correct
* information is sent to the server.
*/
submitButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(isNetworkAvailable(getApplicationContext())) { // If there is an Internet connection available
/*
* A new thread is created from the main one
* to separate the login process (AsyncTask, https operations).
*/
new Thread(new Runnable() {
public void run() {
try {
url = new URL(link);
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
// Create the SSL Connection
SSLContext sc;
sc = SSLContext.getInstance("TLS");
sc.init(null, null, new java.security.SecureRandom());
conn.setSSLSocketFactory(sc.getSocketFactory());
// SSL Authentication
String userpass = usr.getText().toString() + ":" + pass.getText().toString();
String basicAuth = "Basic " + Base64.encodeToString(userpass.getBytes(), Base64.DEFAULT);
conn.setRequestProperty("Authorization", basicAuth);
Log.i("NOTIFICATION", "All SSL parameters set");
// Set timeout and method
conn.setReadTimeout(7000);
conn.setConnectTimeout(7000);
conn.setRequestMethod("POST");
conn.setDoInput(true); // Flag indicating this connection is used for output (POST)
conn.connect();
Log.i("NOTIFICATION", "Connection request sent");
// Check HTTP Response Code
int status = conn.getResponseCode();
InputStream is;
if (status >= 400 ) {
is = conn.getErrorStream();
} else {
is = conn.getInputStream();
}
Log.i("NOTIFICATION", "HTTP Code Checked");
// Receives the answer
resp = null;
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
while((res = rd.readLine()) != null) {
resp += res;
}
Log.i("NOTIFICATION", "Answer received");
Log.i("CODE", resp);
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
} else {
notify = "Internet Connection not available";
}
if(notify != null) {
Toast toast = Toast.makeText(getApplicationContext(), notify, Toast.LENGTH_SHORT);
toast.show();
notify = null;
}
}
});
}
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.poplogin, menu);
return true;
}
}
If you got an HTTP error code it is proof that your HTTPS and therefore SSL setup is working perfectly.
The problem is in the data you're sending. It looks like you need to use a java.net.Authenticator rather than try to do it by hand.

Categories

Resources