I tried c2dm and i need server side - java

I have problem with : Google server said: 401, Unauthorized
I worked on the tomcat server:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;
import com.liferay.portal.kernel.exception.SystemException;
import fr.intuitiv.dal.model.SmartPhone;
import fr.intuitiv.dal.service.SmartPhoneLocalServiceUtil;
public class URLCaller {
public static void callGoogle() throws IOException, SystemException {
URL url = new URL("https://android.clients.google.com/c2dm/send");
StringBuilder builder = new StringBuilder();
byte[] postData = null;
HttpsURLConnection conn = null;
String authorized_Key = getAuthorization();
// For each smartPhone
for(SmartPhone smartPhone : SmartPhoneLocalServiceUtil.getSmartPhones(0, SmartPhoneLocalServiceUtil.getSmartPhonesCount())) {
//Setup data
builder.append("registration_id=" + smartPhone.getRegistrationId());
builder.append("&collapse_key=").append("0");
builder.append("&data.payload=").append("The test work, drink a beer");
postData = builder.toString().getBytes("UTF-8");
//Calling server
conn = (HttpsURLConnection) url.openConnection();
conn.setHostnameVerifier(new CustomizedHostnameVerifier());
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
conn.setRequestProperty("Content_Lenght", Integer.toString(postData.length));
conn.setRequestProperty("Authorization", "GoogleLogin auth=" + authorized_Key);
// Issue the HTTP POST request
System.out.println("" + conn.getOutputStream());
OutputStream out = conn.getOutputStream();
out.write(postData);
out.flush();
System.out.println("Google server said: " + conn.getResponseCode() + ", " + conn.getResponseMessage());
out.close();
}
}
public static String getAuthorization() throws IOException {
// Create the post data
// Requires a field with the email and the password
StringBuilder builder = new StringBuilder();
builder.append("Email=").append(user.config.EMAIL);
builder.append("&Passwd=").append(user.config.PASSWORD);
builder.append("&accountType=GOOGLE");
builder.append("&source=Google-C2DM-Example");
builder.append("&service=ac2dm");// Setup the Http Post
byte[] data = builder.toString().getBytes();
URL url = new URL("https://www.google.com/accounts/ClientLogin");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setUseCaches(false);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", Integer.toString(data.length));
// Issue the HTTP POST request
OutputStream output = conn.getOutputStream();
output.write(data);
output.flush();
// Read the response
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String[] split = reader.readLine().split("=");
// Finally get the authentication token
String clientAuthToken = split[1];
// To something useful with it
output.close();
return clientAuthToken;
}
private static class CustomizedHostnameVerifier implements HostnameVerifier {
#Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
}
}
I get getAuthorization() i have a huge key.
I have my regId from the phone, i send it to the server when i get new one.
I have Android Market and i am log in.
I have registration to the google c2dm.

Are you sure, that this
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String[] split = reader.readLine().split("=");
// Finally get the authentication token
String clientAuthToken = split[1];
// To something useful with it
gives you the part after "Auth="?
Also you should trim the authToken because there might be a \n at the end that messes up the header:
conn.setRequestProperty("Authorization", "GoogleLogin auth=" + StringUtils.trim(authorized_Key));

Related

Minecraft auth server returning 403?

So I'm trying to make a custom launcher for my custom Minecraft client but I need a session id to launch the game. This is the code I'm using to try and get a session ID:
package net.arachnamc;
import org.json.JSONObject;
import java.io.*;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.UUID;
public class Main {
public static void main(String[] args) throws IOException {
String AUTH_SERVER = "https://authserver.mojang.com/authenticate";
String json = String.format(
"{" +
"\"clientToken\":\"%s\"," +
"\"username\":\"%s\"," +
"\"password\":\"%s\"" +
"}",
UUID.randomUUID().toString(),
"Koolade446",
"MyPasswordCensored"
);
JSONObject jso = new JSONObject(json);
System.out.println(json);
URL url = new URL(AUTH_SERVER);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty("Content-Type", "application/json");
OutputStream os = urlConnection.getOutputStream();
os.write(json.getBytes(StandardCharsets.UTF_8));
os.close();
BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
urlConnection.disconnect();
}
}
However, the server returns a 403 forbidden every time. I use a Microsoft account but I can't find any documentation on how to authenticate a Microsoft account so I assumed this was it. Any help is appreciated.

How to fix javax.net.ssl.SSLHandShakeException accessing JIRA

I want to match issues in JIRA with other datasource.
I can use curl:
curl -u myname:mypassword
https://jira.myorganization.com/rest/api/latest/issue/TR-1234
This will return info about the issue, for exampel TR-1234, that I want to check some data for.
In java I want to do the same thing but I get javax.net.ssl.SSLHandShakeException
The program I try to run:
import javax.net.ssl.HttpsURLConnection;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class Main {
public static void main(String[] args) {
URL url = null;
try {
url = new URL("https://jira.myorganization.com/rest/api/latest/issue/TR-1234");
HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
String userpass = "myusername:mypassword";
String basicAuth = "Basic " + new String(Base64.getEncoder().encode(userpass.getBytes()));
con.setRequestProperty ("Authorization", basicAuth);
con.setRequestMethod("GET");
con.setRequestProperty("Accept", "application/json");
System.out.println("Resp="+ con.getResponseCode()+" "+con.getResponseMessage());
String contentType = con.getHeaderField("Content-Type");
BufferedReader br = new BufferedReader(new InputStreamReader(
(con.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
con.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Can I somehow pass userid and password to the URL. The application is a tool and it would be ok to let the user input his name and password.

Java and REST POST method - how to transform URL POST request to JSON Body POST Request?

I have class which works completely and sends POST request successfully toward the external system.
paramaters which are sent currently in the class are:
username:maxadmin
password:sm
DESCRIPTION: REST API test
Now I want to do copy paste of this class and transform it in that way so I could POST request using the JSON body but I am not sure how to do it.
I saw that I should probably have conn.setRequestProperty("Content-Type", "application/json"); instead of application/x-www-form-urlencoded
Can someone please transform my code in order to POST REQUEST using JSON body for parameters sending instead of URL?
This is my 'URL' working class (you will see username/password are in URL while parameters are send in array I have currently only one attribute DESCRIPTION which I am sending)
package com.getAsset;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import org.json.*;
public class GETAssetsPOST {
public static String httpPost(String urlStr, String[] paramName,
String[] paramVal) throws Exception {
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setAllowUserInteraction(false);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
OutputStream out = conn.getOutputStream();
Writer writer = new OutputStreamWriter(out, "UTF-8");
for (int i = 0; i < paramName.length; i++) {
writer.write(paramName[i]);
writer.write("=");
writer.write(URLEncoder.encode(paramVal[i], "UTF-8"));
writer.write("&");
}
writer.close();
out.close();
if (conn.getResponseCode() != 200) {
throw new IOException(conn.getResponseMessage());
}
// Buffer the result into a string
BufferedReader rd = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
rd.close();
conn.disconnect();
return sb.toString();
}
public static void main(String[] args) throws Exception {
String[] attr = new String[1];
String[] value = new String[1];
attr[0] = "DESCRIPTION";
value[0] = "REST API test";
String description = httpPost("http://192.168.150.18/maxrest/rest/os/mxasset/123?_lid=maxadmin&_lpwd=sm",attr,value);
System.out.println("\n"+description);
}
}
Thank you

Login and getting session id of the logged using Https connection in java

I am trying to login to a website using the https requests and then capture the session id. I need this session id inorder to delete some tags in the web application.
Till now I am able to login to the application. After being logged in the application directs me to the home page. This is where I tried to capture the session id from the cookies using https get request to the home page. But unfortunately the cookie doesnot contain session id.
When I send get request to home page after being logged in I get a cookie as :
headers fields are :{null=[HTTP/1.1 200 OK], Server=[Microsoft-IIS/7.0], Pragma=[no-cache], Date=[Wed, 23 Dec 2015 04:37:13 GMT], Serv=[1], Cache-Control=[no-cache, no-store], SI=[1], X-AspNet-Version=[4.0.30319], Set-Cookie=[], Expires=[-1], Content-Length=[255882], X-Powered-By=[ASP.NET], Content-Type=[text/html; charset=utf-8]}
Here the Set-Cookie field is empty.
I have written the following lines of code.
package com.iso.mozart.test.ui;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import javax.net.ssl.HttpsURLConnection;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
public class HttpUrlConnectionExample {
private List<String> cookies;
private HttpsURLConnection conn;
private final String USER_AGENT = "Mozilla/5.0";
public static void main(String[] args) throws Exception {
String url = "https://www.testpurpose.com/Login.aspx";
String homepage = "https://www.testpurpose.com/Home.aspx";
HttpUrlConnectionExample http = new HttpUrlConnectionExample();
// make sure cookies is turn on
CookieHandler.setDefault(new CookieManager());
// 1. Send a "GET" request, so that you can extract the form's data.
String page = http.GetPageContent(url);
String postParams = http.getFormParams(page, "username here", "password here");
// 2. Construct above post's content and then send a POST request for
// authentication
http.sendPost(url, postParams);
// 3. success then go to homepage.
String result = http.GetPageContent(homepage);
System.out.println(result);
}
private void sendPost(String url, String postParams) throws Exception {
URL obj = new URL(url);
conn = (HttpsURLConnection) obj.openConnection();
// Acts like a browser
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Host", "www.testpurpose.com");
conn.setRequestProperty("User-Agent", USER_AGENT);
conn.setRequestProperty("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
conn.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
for (String cookie : this.cookies) {
conn.addRequestProperty("Cookie", cookie.split(";", 1)[0]);
}
conn.setRequestProperty("Connection", "keep-alive");
conn.setRequestProperty("Referer", url);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", Integer.toString(postParams.length()));
conn.setDoOutput(true);
conn.setDoInput(true);
// Send post request
DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes(postParams);
wr.flush();
wr.close();
int responseCode = conn.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + postParams);
System.out.println("Response Code : " + responseCode);
// System.out.println("HEADERS:"+conn.getRequestMethod());
BufferedReader in =
new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// System.out.println(response.toString());
}
private String GetPageContent(String url) throws Exception {
URL obj = new URL(url);
conn = (HttpsURLConnection) obj.openConnection();
// default is GET
conn.setRequestMethod("GET");
conn.setUseCaches(false);
// act like a browser
conn.setRequestProperty("User-Agent", USER_AGENT);
conn.setRequestProperty("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
conn.getRequestProperties();
conn.setDoOutput(true);
// System.out.println("Huhahahahah :"+conn.getHeaderFields());
if (cookies != null) {
for (String cookie : this.cookies) {
conn.addRequestProperty("Cookie", cookie.split(";", 1)[0]);
}
}
int responseCode = conn.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("headers fields are :"+conn.getHeaderFields());
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// Get the response cookies
setCookies(conn.getHeaderFields().get("Set-Cookie")); //This is where I have tried to capture the session id from cookie but could it doesnot contain session id.
return response.toString();
}
public String getFormParams(String html, String username, String password)
throws UnsupportedEncodingException {
System.out.println("Extracting form's data...");
Document doc = Jsoup.parse(html);
// Google form id
Element loginform = doc.getElementById("form1");
Elements inputElements = loginform.getElementsByTag("input");
List<String> paramList = new ArrayList<String>();
for (Element inputElement : inputElements) {
String key = inputElement.attr("name");
String value = inputElement.attr("value");
if (key.equals("txtUserID"))
value = username;
else if (key.equals("txtPassword"))
value = password;
paramList.add(key + "=" + URLEncoder.encode(value, "UTF-8"));
}
// build parameters list
StringBuilder result = new StringBuilder();
for (String param : paramList) {
if (result.length() == 0) {
result.append(param);
} else {
result.append("&" + param);
}
}
return result.toString();
}
public List<String> getCookies() {
return cookies;
}
public void setCookies(List<String> cookies) {
this.cookies = cookies;
}
}
CookieHandler.setDefault(new CookieManager());
Change above line in your code with this line.
CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL));
Let me know if that works for you.
HttpSession session = request.getSession();
String sessionid = session.getId();
use this small block of code.

facebook login using java

I am looking for a way to login to Facebook without a browser.
I want to obtain the access token without a browser.
Login is required in order to obtain the access token.
-Login Java examples
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import javax.net.ssl.HttpsURLConnection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
public class HttpUrlConnectionExample {
private List<String> cookies;
private HttpsURLConnection conn;
private final String USER_AGENT = "Mozilla/5.0";
public static void main(String[] args) throws Exception {
String url = "https://www.facebook.com/login.php?login_attempt=1";
String facebook = "https://www.facebook.com/";
HttpUrlConnectionExample http = new HttpUrlConnectionExample();
// make sure cookies is turn on
CookieHandler.setDefault(new CookieManager());
// 1. Send a "GET" request, so that you can extract the form's data.
String page = http.GetPageContent(url);
String postParams = http.getFormParams(page, "sainstia#gmail.com", "1111");
// 2. Construct above post's content and then send a POST request for
// authentication
http.sendPost(url, postParams);
// 3. success then go to facebook.
String result = http.GetPageContent(facebook);
try {
String content = result;
File file = new File(".\\facebook_page.html");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
}
private void sendPost(String url, String postParams) throws Exception {
URL obj = new URL(url);
conn = (HttpsURLConnection) obj.openConnection();
// Acts like a browser
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Host", "www.facebook.com");
conn.setRequestProperty("User-Agent", USER_AGENT);
conn.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
conn.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
for (String cookie : this.cookies) {
conn.addRequestProperty("Cookie", cookie.split(";", 1)[0]);
}
conn.setRequestProperty("Connection", "keep-alive");
conn.setRequestProperty("Referer", "https://www.facebook.com/login.php?login_attempt=1");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", Integer.toString(postParams.length()));
conn.setDoOutput(true);
conn.setDoInput(true);
// Send post request
DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes(postParams);
wr.flush();
wr.close();
int responseCode = conn.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + postParams);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// System.out.println(response.toString());
}
private String GetPageContent(String url) throws Exception {
URL obj = new URL(url);
conn = (HttpsURLConnection) obj.openConnection();
// default is GET
conn.setRequestMethod("GET");
conn.setUseCaches(false);
// act like a browser
conn.setRequestProperty("User-Agent", USER_AGENT);
conn.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
conn.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
if (cookies != null) {
for (String cookie : this.cookies) {
conn.addRequestProperty("Cookie", cookie.split(";", 1)[0]);
}
}
int responseCode = conn.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// Get the response cookies
setCookies(conn.getHeaderFields().get("Set-Cookie"));
return response.toString();
}
public String getFormParams(String html, String username, String password) throws UnsupportedEncodingException {
System.out.println("Extracting form's data...");
Document doc = Jsoup.parse(html);
// Google form id
Element loginform = doc.getElementById("login_form");
Elements inputElements = loginform.getElementsByTag("input");
List<String> paramList = new ArrayList<String>();
for (Element inputElement : inputElements) {
String key = inputElement.attr("name");
String value = inputElement.attr("value");
if (key.equals("email"))
value = username;
else if (key.equals("pass"))
value = password;
paramList.add(key + "=" + URLEncoder.encode(value, "UTF-8"));
}
// build parameters list
StringBuilder result = new StringBuilder();
for (String param : paramList) {
if (result.length() == 0) {
result.append(param);
} else {
result.append("&" + param);
}
}
return result.toString();
}
public List<String> getCookies() {
return cookies;
}
public void setCookies(List<String> cookies) {
this.cookies = cookies;
}
}
GetPageContent (String url) {
.....
.....
  setCookies (. conn.getHeaderFields () get ("Set-Cookie"));
......
}
I could not have a "Set-Cookie" value.
I can not find the "Set-Cookie".
What should I do to solve this problem?
You should use Jsoup i just finished making a program that did exactly this it logged onto a website and then i could manipulate anything on the website as i needed as long as you match the GETrequests you can log on to the wesbsite like this.
Connection.Response response = Jsoup.connect(url).method(Connection.Method.GET).execute();
response = Jsoup.connect(url)
.cookies(response.cookies())
.data("Action", "Login")
.data("User", "My_UserName")
.data("Password", "My_Password")
.method(Connection.Method.POST)
.followRedirects(true)
.timeout(50000)
.execute();

Categories