kerberos fallback to ntlm java code - java

I am working on Microsoft Sharepoint integration with SAP. The sharepoint supports 'kerberos fallback to ntlm' method for authentication.
I wish to take advantage of ntlm authentication, as I dont wish to go into kerberos set up. My understanding is that ntlm authentication can be managed with following piece of code however, I am getting '401 Unauthorized' error.
Probably something needs to be added to following line in password authentication.
if (getRequestingScheme().equalsIgnoreCase("negotiate") || getRequestingScheme().equalsIgnoreCase("ntlm") || getRequestingScheme().equalsIgnoreCase("kerberos"))
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Authenticator;
import java.net.HttpURLConnection;
import java.net.PasswordAuthentication;
import java.net.URL;
import java.lang.Object;
import java.nio.charset.StandardCharsets;
import java.io.OutputStream;
import java.net.InetAddress;
public class Main {
public static void main(String[] argv) throws Exception {
Authenticator.setDefault(new MyAuthenticator());
URL url = new URL ("https://sharepointlink");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput( true );
//conn.setInstanceFollowRedirects( false );
conn.setRequestMethod( "POST" );
conn.setRequestProperty("Accept", "*/*");
//MyAuthenticator m = new MyAuthenticator();
String urlParameters = "tests";
byte[] postData = urlParameters.getBytes( StandardCharsets.UTF_8 );
int postDataLength = postData.length;
byte[] data = ("").getBytes("UTF-8");
OutputStream out = conn.getOutputStream();
out.write(postData);
out.flush();
StringBuilder response = new StringBuilder();
InputStream stream = conn.getInputStream();
// InputStream estream = conn.getErrorStream();
BufferedReader in = new BufferedReader(new InputStreamReader(stream));
String str = "";
while ((str = in.readLine()) != null) {
response.append(str) ;
}
in.close();
System.out.println(response.toString());
// return response.toString() ;
}
}
class MyAuthenticator extends Authenticator {
// static String user = System.getProperty("user");
// static String pass = System.getProperty("pass");
// static String kuser = System.getProperty("kuser");
// static String kpass = System.getProperty("kpass");
// static String showhint = System.getProperty("showhint");
protected PasswordAuthentication getPasswordAuthentication() {
String promptString = getRequestingPrompt();
System.out.println("prompt string " + promptString);
String hostname = getRequestingHost();
System.out.println("host name " + hostname);
InetAddress ipaddr = getRequestingSite();
System.out.println(ipaddr);
int port = getRequestingPort();
RequestorType reqType = getRequestorType();
System.out.println ("reqeust type = " + reqType.toString());
System.out.println ("Protocol type = " + getRequestingProtocol());
System.out.println ("Scheme type = " + getRequestingScheme());
if (getRequestingScheme().equalsIgnoreCase("negotiate") || getRequestingScheme().equalsIgnoreCase("ntlm") || getRequestingScheme().equalsIgnoreCase("kerberos")) {
String krb5user="tp1\\user";
String krb5pass ="pwd";
// get krb5user and krb5pass in your own way
return (new PasswordAuthentication (krb5user, krb5pass.toCharArray()));
}
String username = "TP1\\user";
String password = "pwd";
return new PasswordAuthentication(username, password.toCharArray());
}
}
Can anyone help please.

Related

Yandex Api not translating properly in eclipse

Here is my code in TranslateAPI.java:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;
public class TranslateAPI {
public static final String API_KEY = "pdct.1.1.20180924T090857Z.3e14b8b207704aef.9bdc409229b123003526815bb7062ed42616f26a";
private static String request(String URL) throws IOException {
URL url = new URL(URL);
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
InputStream inStream = urlConn.getInputStream();
String recieved = new BufferedReader(new InputStreamReader(inStream)).readLine();
System.setProperty("http.agent", "Chrome");
String agent = java.security.AccessController.doPrivileged(new sun.security.action.GetPropertyAction("http.agent"));
inStream.close();
return recieved;
}
public static Map<String, String> getLangs() throws IOException {
String langs = request("https://translate.yandex.net/api/v1.5/tr.json/getLangs?key=" + API_KEY + "&ui=en");
langs = langs.substring(langs.indexOf("langs")+7);
langs = langs.substring(0, langs.length()-1);
String[] splitLangs = langs.split(",");
Map<String, String> languages = new HashMap<String, String>();
for (String s : splitLangs) {
String[] s2 = s.split(":");
String key = s2[0].substring(1, s2[0].length()-1);
String value = s2[1].substring(1, s2[1].length()-1);
languages.put(key, value);
}
return languages;
}
public static String translate(String text, String sourceLang, String targetLang) throws IOException {
String response = request("https://translate.yandex.net/api/v1.5/tr.json/translate?key=" + API_KEY + "&text=" + text + "&lang=" + sourceLang + "-" + targetLang);
return response.substring(response.indexOf("text")+8, response.length()-3);
}
AND in workerthread.java:
String s=TranslateAPI.detectLanguage(abc);
System.out.println(s);
However,I am getting the follwing errror:
Server returned HTTP response code: 403 for URL: https://translate.yandex.net/api/v1.5/tr.json/detect?key=pdct.1.1.20180924T090857Z.3e14b8b207704aef.9bdc409229b123003526815bb7062ed42616f26a&text=cat
Can you please help? Thanks in advance
You are getting a 401 Error thus Your API Key is Invalid,
You can always go to Yandex's Developers page to get a new one.
Its always great to publish your private API here :D

Implementation of Kraken API in Java

So I currently working on an implementation of the Kraken API for Java. I am using this sample code I found on http://pastebin.com/nHJDAbH8.
The general usage as described by Kraken (https://www.kraken.com/help/api) is:
API-Key = API key
API-Sign = Message signature using HMAC-SHA512 of
( URI path + SHA256( nonce + POST data ) ) and base64 decoded secret API
key
and
nonce = always increasing unsigned 64 bit integer
otp = two-factor password ( if two-factor enabled, otherwise not required )
however I am facing the following response:
{"error":["EAPI:Invalid key"]}
I already tried a couple of ways ( getting a new API, trying to change the sha256 methods, because I thought something is wrong with the way it is hashed )
So this is the code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
public class KrakenClient {
protected static String key = "myAPIKey"; // API key
protected static String secret = "MySecret===="; // API secret
protected static String url = "api.kraken.com"; // API base URL
protected static String version = "0"; // API version
public static void main(String[] args) throws Exception {
queryPrivateMethod("Balance");
}
public static void queryPrivateMethod(String method) throws NoSuchAlgorithmException, IOException{
long nonce = System.currentTimeMillis();
String path = "/" + version + "/private/" + method; // The path like "/0/private/Balance"
String urlComp = "https://"+url+path; // The complete url like "https://api.kraken.com/0/private/Balance"
String postdata = "nonce="+nonce;
String sign = createSignature(nonce, path, postdata);
postConnection(urlComp, sign, postdata);
}
/**
* #param nonce
* #param path
* #param postdata
* #return
* #throws NoSuchAlgorithmException
* #throws IOException
*/
private static String createSignature(long nonce, String path,
String postdata) throws NoSuchAlgorithmException, IOException {
return hmac(path+sha256(nonce + postdata), new String(Base64.decodeBase64(secret)));
}
public static String sha256Hex(String text) throws NoSuchAlgorithmException, IOException{
return org.apache.commons.codec.digest.DigestUtils.sha256Hex(text);
}
public static byte[] sha256(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException{
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(text.getBytes());
byte[] digest = md.digest();
return digest;
}
public static void postConnection(String url1, String sign, String postData) throws IOException{
URL url = new URL( url1 );
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.addRequestProperty("API-Key", key);
connection.addRequestProperty("API-Sign", Base64.encodeBase64String(sign.getBytes()));
// connection.addRequestProperty("API-Sign", sign);
connection.addRequestProperty("User-Agent", "Mozilla/4.0");
connection.setRequestMethod( "POST" );
connection.setDoInput( true );
connection.setDoOutput( true );
connection.setUseCaches( false );
// connection.setRequestProperty( "Content-Type",
// "application/x-www-form-urlencoded" );
connection.setRequestProperty( "Content-Length", String.valueOf(postData.length()) );
OutputStreamWriter writer = new OutputStreamWriter( connection.getOutputStream() );
writer.write( postData );
writer.flush();
BufferedReader reader = new BufferedReader(
new InputStreamReader(connection.getInputStream()) );
for ( String line; (line = reader.readLine()) != null; )
{
System.out.println( line );
}
writer.close();
reader.close();
}
public static String hmac(String text, String secret){
Mac mac =null;
SecretKeySpec key = null;
// Create a new secret key
try {
key = new SecretKeySpec( secret.getBytes( "UTF-8"), "HmacSHA512" );
} catch( UnsupportedEncodingException uee) {
System.err.println( "Unsupported encoding exception: " + uee.toString());
return null;
}
// Create a new mac
try {
mac = Mac.getInstance( "HmacSHA512" );
} catch( NoSuchAlgorithmException nsae) {
System.err.println( "No such algorithm exception: " + nsae.toString());
return null;
}
// Init mac with key.
try {
mac.init( key);
} catch( InvalidKeyException ike) {
System.err.println( "Invalid key exception: " + ike.toString());
return null;
}
// Encode the text with the secret
try {
return new String( mac.doFinal(text.getBytes( "UTF-8")));
} catch( UnsupportedEncodingException uee) {
System.err.println( "Unsupported encoding exception: " + uee.toString());
return null;
}
}
}
Here is a working example:
static String key = "---myKey---";
static String secret = "---mySecret---";
String nonce, signature, data, path;
static String domain = "https://api.kraken.com";
void account_balance() {
nonce = String.valueOf(System.currentTimeMillis());
data = "nonce=" + nonce;
path = "/0/private/Balance";
calculateSignature();
String answer = post(domain + path, data);
// on empty accounts, returns {"error":[],"result":{}}
// this is a known Kraken bug
...
}
String post(String address, String output) {
String answer = "";
HttpsURLConnection c = null;
try {
URL u = new URL(address);
c = (HttpsURLConnection)u.openConnection();
c.setRequestMethod("POST");
c.setRequestProperty("API-Key", key);
c.setRequestProperty("API-Sign", signature);
c.setDoOutput(true);
DataOutputStream os = new DataOutputStream(c.getOutputStream());
os.writeBytes(output);
os.flush();
os.close();
BufferedReader br = null;
if(c.getResponseCode() >= 400) {
System.exit(1);
}
br = new BufferedReader(new InputStreamReader((c.getInputStream())));
String line;
while ((line = br.readLine()) != null)
answer += line;
} catch (Exception x) {
System.exit(1);
} finally {
c.disconnect();
}
return answer;
}
void calculateSignature() {
signature = "";
try {
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update((nonce + data).getBytes());
Mac mac = Mac.getInstance("HmacSHA512");
mac.init(new SecretKeySpec(Base64.decodeBase64(secret.getBytes()), "HmacSHA512"));
mac.update(path.getBytes());
signature = new String(Base64.encodeBase64(mac.doFinal(md.digest())));
} catch(Exception e) {}
return;
}

How to Get the Auth Token of Skype using HttpURLConnection

I'm trying to login to my user in Skype using HttpURLConnection class in JAVA. My objective is to get the Auth token(Which expires every 24hours) for my user. I'm following the Request cookies that are being sent in every HTTP call and sending the same set of cookies in JAVA program. But when response is received, there is a difference in the cookies received by the HTTP call made when I login through browser and HttpURLConnection class.
Can anyone help on this?
/**
* Created by shreyas on 23/09/15.
*/
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class HttpsURLConnection {
public static void main(String[] args) throws Exception{
String httpsURL = "https://login.skype.com/login?client_id=578134&redirect_uri=https%3A%2F%2Fweb.skype.com&intsrc=client-_-webapp-_-production-_-go-signin&message=logged_out&lc=16393";
String query = "username="+URLEncoder.encode("username","UTF-8");
query += "&";
query += "password="+URLEncoder.encode("password","UTF-8") ;
String cookies = "MSFPC=ID=7257d650ce6da54f8f16951c796b637f&CS=3&LV=201508&V=1; SWACC=TM=1442036652; tracking=1443005674353; mbox=PC#1441957179127-901122.28_13#1445597676|session#1443005606468-117694#1443007536|check#true#1443005736; frmrgtpe=1-3; lastLogin=SK; skype-session=5a490f691979c9d9cfc9b592d8efe2b3828feb29; skype-session-token=ed386369f29ac162d028d11fe4d6f365b462ba1c; SC=CC=:CCY=EUR:ENV=:LC=en:LIM=:RS=m:TM=1444300641:TS=1444300641:TZ=:UCP=:VAT=:VER=; s_vi=[CS]v1|2AEE1E5585489697-60000103A002F05F[CE]; s_pers=%20s_fid%3D47DE135BD66B6E10-3A8420CADAC57A3E%7C1507459045330%3B%20gpv_p23%3Dskypeloginweb%252Faccount%252Flogin%7C1444302445338%3B%20s_nr%3D1444300645341-Repeat%7C1507372645341%3B; s_sess=%20s_ria%3Dflash%252019%257C%3B%20s_cc%3Dtrue%3B%20s_sq%3D%3B";
// String payload="{\"username\":\"username\",\"method\":\"UnifiedMVP2\", \"password\":\"password\", \"timezone_field\":\"+05|30\", \"js_time\":\"1444029538.658\", \"session_token\":\"448f4256096509ca35740235e7b78f3306156c97\", \"client_id\":\"578134\", \"redirect_uri\":\"https://web.skype.com\", \"pie\":\"7iw9lnVzLBaE3pIAFTD+Wn6rY17lkifj+9rXTt8LAFcMaex++atApZ6r404safgR8cxliXnLP3PF2Gqd9HKwjzA2NDIzNTI5M2I0YjliZTMxYWE1NjYzMWYwNjRmNzdh\", \"etm\":\"+oMsu5T+fvyJC89yhfDfhduvhoAx2RzS84mqD43PNz5sepudpPTo2KLGoKXEei7Ee9gpvgZj2W2H/Uc+O+f8oDkyZTJlZDAyOTg4NDExM2QxNzllZmU4NjkyOTFjMmU4\" }";
URL myurl = new URL(httpsURL);
HttpURLConnection con = (HttpURLConnection)myurl.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Cookies",cookies);
con.setRequestProperty("Content-length", String.valueOf(query.length()));
con.setRequestProperty("Content-Type","application/x-www- form-urlencoded");
con.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0;Windows98;DigExt)");
// con.connect();
con.setDoOutput(true);
DataOutputStream output = new DataOutputStream(con.getOutputStream());
output.writeBytes(query);
// output.writeBytes(payload);
output.close();
try{
con.setDoInput(true);
}
catch (IllegalStateException e){
System.out.print("\nIllegal State Exception \n"+e);
}
DataInputStream input = new DataInputStream( con.getInputStream() );
for( int c = input.read(); c != -1; c = input.read() )
System.out.print( (char)c );
input.close();
System.out.println("Response Code :"+con.getResponseCode());
System.out.println("Response Message :"+ con.getResponseMessage());
Map<String, List<String>> headerFields = con.getHeaderFields();
Set<String> headerFieldsSet = headerFields.keySet();
Iterator<String> hearerFieldsIter = headerFieldsSet.iterator();
while (hearerFieldsIter.hasNext()) {
String headerFieldKey = hearerFieldsIter.next();
if ("Set-Cookie".equalsIgnoreCase(headerFieldKey)) {
List<String> headerFieldValue = headerFields.get(headerFieldKey);
int n= headerFieldValue.size();
System.out.println("Number of cookies="+n);
for (String headerValue : headerFieldValue) {
System.out.println("Cookie Found...");
String[] fields = headerValue.split(";\r*|;\n*|;\t*|;\f*");
//System.out.println("header Value="+headerValue);
String cookieValue = fields[0];
String expires = null;
String path = null;
String domain = null;
boolean secure = false;
// Parse each field
for (int j = 1; j < fields.length; j++) {
if ("secure".equalsIgnoreCase(fields[j])) {
secure = true;
}
else if (fields[j].indexOf('=') > 0) {
String[] f = fields[j].split("=");
if ("expires".equalsIgnoreCase(f[0])) {
expires = f[1];
}
else if ("domain".equalsIgnoreCase(f[0])) {
domain = f[1];
}
else if ("path".equalsIgnoreCase(f[0])) {
path = f[1];
}
}
}
System.out.println("cookieValue:" + cookieValue);
System.out.println("expires:" + expires);
System.out.println("path:" + path);
System.out.println("domain:" + domain);
System.out.println("secure:" + secure);
System.out.println("*****************************************");
}
}
}
System.out.println("Response Code :"+con.getResponseCode());
System.out.println("Response Message :"+ con.getResponseMessage());
}
}

java.io.exception...http exception 403

Can someone help me.I am using the below piece of code for accessing a webpage for which i had access through a browser with some user password authentication.
But when i tried the same i got 403 exception, am i doing this wrong?
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.net.PasswordAuthentication;
import java.net.Authenticator;
import java.net.InetAddress;
import java.lang.reflect.Proxy;
import java.lang.System;
import sun.misc.*;
import java.net.HttpURLConnection;
public class summa {
//static final String kuser = " "; // your account name
static final String kpass = " "; // your password for the account
//static class MyAuthenticator extends Authenticator {
//public PasswordAuthentication getPasswordAuthentication() {
// I haven't checked getRequestingScheme() here, since for NTLM
// and Negotiate, the usrname and password are all the same.
//System.err.println("Feeding username and password for " + //getRequestingScheme());
//return (new PasswordAuthentication(kuser, kpass.toCharArray()));
//}
//}
public static void main(String[] args) {
try {
URL google = new URL("http://www.google.com/");
HttpURLConnection yc =(HttpURLConnection)google.openConnection();
System.setProperty("http.proxyHost","171.160.82.70") ;
System.setProperty("http.proxyPort", "80") ;
String userPassword = " ";
String encoding = new sun.misc.BASE64Encoder().encode (userPassword.getBytes());
//Authenticator.setDefault(new MyAuthenticator());
yc.setRequestProperty ("Authorization", "Basic " + encoding);
yc.setRequestProperty(userPassword, encoding);
yc.addRequestProperty("User-Agent","ie-7 (compatible; MSIE 6.0; Windows NT 5.0)");
BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
String inputLine="s";
inputLine=in.readLine();
System.out.println(inputLine);
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
See HTTP 403: Forbidden.

Execution stops automatically at getOutputStream() function Push notification using servlets

I have a problem while getting a push notification on the server side. I am using C2DM sever connection to achieve the push notification. Its working fine on android but not in the Java Servecr. I'm able to get the registration ID and authentication code but the handling stops when it comes to the line:
OutputStream out = conn.getOutputStream();
It does not throw anything, just stops.
If anyone has a solution for this then please guide me. I am adding the whole code so you can go through and tell me where I'm wrong in getting the result.
import org.apache.http.client.methods.HttpPost;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import javax.net.ssl.HttpsURLConnection;
import javax.print.DocFlavor.INPUT_STREAM;
import org.apache.http.HttpClientConnection;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.DefaultHttpClientConnection;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
public class Server {
private static String key=null;
// 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";
private static String Authcode = null;
// Registration is currently hardcoded
private final static String YOUR_REGISTRATION_STRING = "reg id";
public void getAuthentification() {
System.out.println("check");
//HttpPost post = new HttpPost("http://www.google.com/accounts/ClientLogin");
try {
System.getProperties().put("proxySet", true);
System.getProperties().put("proxyHost","proxy" );
System.getProperties().put("proxyPort","8080");
System.out.println("getAuthentication method called****************************");
URL url=new URL("https://www.google.com/accounts/ClientLogin");
URLConnection connection=url.openConnection();
connection.setDoOutput(true);
HttpURLConnection conn=(HttpURLConnection)connection;
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(true);
StringBuilder content = new StringBuilder();
content.append("Email=").append("xyz#gmail.com");
content.append("&Passwd=").append("asdfgt");
content.append("&service=").append("ac2dm");
content.append("&source=").append("MY_APP-V0.1");
content.append("&accountType=").append("HOSTED_OR_GOOGLE");
OutputStream out = conn.getOutputStream();
out.write(content.toString().getBytes("UTF-8"));
out.close();
int res = conn.getResponseCode();
System.out.println(res + "Success");
StringBuffer resp = new StringBuffer();
if(res == HttpsURLConnection.HTTP_OK){
InputStream in = conn.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(in));
String line = "";
while ((line = rd.readLine()) != null) {
System.out.println(line);
System.out.println("inside");
if (line.startsWith("Auth=")) {
Authcode = line.substring(5);
resp.append(line.substring(5));
System.out.println(line.substring(5));
System.out.println("something to be done here..");
}
}
rd.close();
}
}
}
public void sendMessage() {
try {
System.out.println(YOUR_REGISTRATION_STRING);
System.out.println("Authcode = " + Authcode);
System.getProperties().put("proxySet", true);
System.getProperties().put("proxyHost","proxy" );
System.getProperties().put("proxyPort","8080");
URL url1 = new URL("https://android.apis.google.com/c2dm/send");
System.out.println("here2.5");
HttpURLConnection conn1 = (HttpURLConnection) url1.openConnection();
System.out.println("here2.6");
conn1.setDoInput(true);
conn1.setDoOutput(true);
conn1.setUseCaches(false);
conn1.setRequestMethod("POST");
conn1.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
conn1.setRequestProperty("Authorization", "GoogleLoginauth="+ Authcode);
System.out.println("here2.7");
OutputStream out = conn1.getOutputStream();
System.out.println("send Message method.");
String auth_key="n/a";
if(key!=null) {
auth_key=Authcode;
}
System.out.println("here");
// Send a sync message to this Android device.
StringBuilder postDataBuilder = new StringBuilder();
postDataBuilder.append(PARAM_REGISTRATION_ID)
.append("=").append(YOUR_REGISTRATION_STRING);
System.out.println("here1");
postDataBuilder.append("&").append(PARAM_COLLAPSE_KEY)
.append("=").append("0");
System.out.println("here2");
postDataBuilder.append("&").append("data.payload")
.append("=").append(URLEncoder.encode("Lars war hier", UTF8));
byte[] postData = postDataBuilder.toString().getBytes(UTF8);
conn1.setRequestProperty("Content-Length",
Integer.toString(postData.length));
// Hit the dm URL.
System.out.println("out created");
out.write(postData);
System.out.println("data written");
out.close();
System.out.println("here3");
int responseCode = conn1.getResponseCode();
System.out.println(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.
System.out.println("C2DM, Unauthorized - need token");
}
} catch (Exception ignore) {
// the editor that corrected the indentation of the code could not find any code here so he closed all methods to have a syntactically correct class.
}
}
}
Make sure that you are posting message to url from background thread not from the UI thread.
I hope after this change it will work. Good Luck!!!

Categories