Log in to facebook using httpurlconnection - java

I'm trying to login to facebook using httpurlconnect. I think i need to get the cookie from facebook.com/ajax/bz and then pass it along with my login attempt but maybe not. The response just takes me back to the login page and I never log in. Can someone help me get this to log in?
I do not want to use the official API.
private String getRequestCookie() throws IOException {
// URL myUrl = new URL("http://www.hccp.org/cookieTest.jsp");
/* URLConnection urlConn = null;
try {
urlConn = url.openConnection(currentProxy);
urlConn.connect();
} catch (IOException e) {
e.printStackTrace();
}*/
String cookies = "";
URL myUrl = new URL("https://www.facebook.com/ajax/bz");
URLConnection urlConn = myUrl.openConnection();
urlConn.connect();
String headerName=null;
for (int i=1; (headerName = urlConn.getHeaderFieldKey(i))!=null; i++) {
if (headerName.equals("Set-Cookie")) {
String cookie = urlConn.getHeaderField(i);
cookie = cookie.substring(0, cookie.indexOf(";"));
String cookieName = cookie.substring(0, cookie.indexOf("="));
String cookieValue = cookie.substring(cookie.indexOf("=") + 1, cookie.length());
cookies = cookies+cookieName+"="+cookieValue+"; ";
//cookieNameList.add(cookieValue);
System.out.println("da cookies:" + cookies);
return cookies;
}
}
// must have failed yo
cookies = "failed";
return cookies;
}
private String performJsonPost() {
try {
String cookies = getRequestCookie();
String query = "email=EMAILNAME%40EMAIL.com&pass=PASSWORD&lsd=AVrVVnf1&default_persistent=0&timezone=&lgnrnd=132329_hCSS&lgnjs=n&locale=tr_TR";
URL urls = new URL("https://www.facebook.com/login.php?login_attempt=1");
final HttpURLConnection conn = (HttpURLConnection)urls.openConnection();
final byte[] payloadAsBytes = query.getBytes(Charset.forName("UTF-8"));
conn.setConnectTimeout(15000);
conn.setReadTimeout(15000);
conn.setRequestMethod("POST");
conn.setRequestProperty("Cookie", "reg_fb_gate=https%3A%2F%2Fwww.facebook.com%2F; reg_fb_ref=https%3A%2F%2Fwww.facebook.com%2F; reg_ext_ref=deleted; Max-Age=0; datr=0aFzVK8Fu0Gl7M8cn_6TSqlZ");
conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:25.0) Gecko/20100101 Firefox/25.0");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", "" + payloadAsBytes.length);
conn.setRequestProperty("Content-Language", "en-US");
conn.setUseCaches(false);
conn.setDoInput(true);
conn.setDoOutput(true);
final DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());
outStream.write(payloadAsBytes);
// outStream.write(payloadAsBytes);
outStream.flush();
outStream.close();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
/* catch (Exception e2) {
//inStream = conn.getErrorStream();
}*/
final StringBuilder response = new StringBuilder();
final byte[] buffer = new byte[1024];
int bytesRead;
//System.out.println(inStream.toString() + "WHAT ARE U SAYING BRO");
//while ((bytesRead = inStream.read(buffer)) > 0) {
//response.append(new String(buffer, "UTF-8").substring(0, bytesRead));
while ((line = rd.readLine()) != null) {
System.out.println(line);
response.append(line);
// inStream = conn.getInputStream();
}
return response.toString();
}catch (IOException e) {
e.printStackTrace();
return null;
}
// System.out.println("Response!:"+response.toString());
// return response.toString();
}
catch (IOException e) {
e.printStackTrace();
return null;
}
}

It doesn't matter that you want to do it; according to the Automated Data Collection Terms, it's not allowed. You app/server can be blocked. Don't do this. Instead, just use the Graph API and all documented features.

Related

How to call subsequent request using j_security_check

How to call subsequent requests using j_security_check, I have followed below code but it's not working .
String url = "https://myhost/jsp/j_security_check?j_username=myuser&j_password=mypassword";
HttpURLConnection connection = (HttpURLConnection) new
URL(url).openConnection();
if (connection.getResponseCode() == 200) {
String cookie = connection.getHeaderField("Set-Cookie").split(";", 2)[0];
url = "https://myhost/getusers";
connection = (HttpURLConnection) new URL(url).openConnection();
connection.setRequestProperty("Cookie", cookie);
connection.setRequestProperty("Cache-Control", "no-cache");
InputStream input = connection.getInputStream();
try (BufferedReader buffer = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
String result = buffer.lines().collect(Collectors.joining("\n"));
System.out.println(result);
} catch (Exception e) {
e.printStackTrace();
}
}
Can anyone help me on it.

java get response from PayU api poland

I'm trying to integrate payu poland payment system to my website but cant get success response. Website done by jsp. Here is link that payu gave for help click im using "create a new order" for configuration. But its not retrieving any answer. Could anywane help me? Here is my jsp code:
`public static String sendPostRequest2(String requestUrl, String payload, String x, String y) {
StringBuilder jsonString = new StringBuilder();
try {
URL url = new URL(requestUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
try (OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), "UTF-8")) {
writer.write(payload);
}
connection.setRequestProperty(x, y);
try (BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
String line;
while ((line = br.readLine()) != null) {
jsonString.append(line);
jsonString.append("<br>\n");
}
}
connection.disconnect();
} catch (IOException e) {
try {
URL url = new URL(requestUrl);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
InputStream is;
if (httpConn.getResponseCode() >= 400) {
is = httpConn.getErrorStream();
} else {
is = httpConn.getInputStream();
}
try (BufferedReader br = new BufferedReader(new InputStreamReader(is))) {
String line;
while ((line = br.readLine()) != null) {
jsonString.append(line);
jsonString.append("<br>\n");
}
}
jsonString.append(new RuntimeException(e.getMessage()));
} catch (MalformedURLException ex) {
jsonString.append(new RuntimeException(ex.getMessage()));
Logger.getLogger(PayU.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
jsonString.append(new RuntimeException(ex.getMessage()));
Logger.getLogger(PayU.class.getName()).log(Level.SEVERE, null, ex);
}
}
return jsonString.toString();
}
public static String get() {
String x = "";
String payload2 = "{ 'notifyUrl': 'https://your.eshop.com/notify', 'customerIp': '127.0.0.1', 'merchantPosId': '145227', 'description': 'RTV market', 'currencyCode': 'PLN', 'totalAmount': '21000', 'products': [ { 'name': 'Wireless mouse', 'unitPrice': '15000', 'quantity': '1' }, { 'name': 'HDMI cable', 'unitPrice': '6000', 'quantity': '1' } ]}";
String requestUrl2 = "https://secure.payu.com/api/v2_1/orders/";
x += sendPostRequest2(requestUrl2, payload2, "Authorization", "Bearer 3e5cac39-7e38-4139-8fd6-30adc06a61bd");
return x;
}`
set the redirect turn off after that you will get the json response. So in your java code set redirect false.
connection.setInstanceFollowRedirects(false);

I am getting 411 HTTP Error while using POST method in Java

I am facing a problem while using POST Method in Java nowadays. I am receiving
Exception in thread "main" java.lang.RuntimeException: Server returned HTTP response code: 411 for URL.
I couldn't find any available document anywhere. None of them were useful. How do I fix it?
My code
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class req {
public static void main(String[] args) {
sendPostRequest(requestURL);
}
private static String sendPostRequest(String requestUrl) {
StringBuilder jsonString = new StringBuilder();
try {
URL url = new URL(requestUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
byte[] data = requestUrl.getBytes("UTF-8");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
connection.setRequestProperty("Content-Length", String.valueOf(data.length));
connection.setRequestProperty("Authorization", "Basic " + "usename:password");
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = br.readLine()) != null) {
jsonString.append(line);
}
br.close();
connection.disconnect();
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
return jsonString.toString();
}
}
Perfectly working method:
public String sendPostRequest(String requestURL, HashMap<String, String> postDataParams) {
URL url;
String response = "";
try {
url = new URL(requestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));
writer.flush();
writer.close();
os.close();
int responseCode=conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream()));
response = br.readLine();
}
else {
response="Error Registering";
}
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
boolean first = true;
for(Map.Entry<String, String> entry : params.entrySet()){
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
return result.toString();
}
If you are returning a JSON in your response:
public JSONObject getPostResult(String json){
if(!json.isEmpty()) {
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON_ERROR", "Error parsing data " + e.toString());
}
}
return jObj;
}
If you are still having trouble, maybe this will help. I did not test, machine does not have java installed.
You should also set all other headers that you need.
public static String PostRequest(String requestUrl, String username, String password) {
StringBuilder jsonString = new StringBuilder();
HttpURLConnection connection = null;
try {
URL url = new URL(requestUrl);
connection = (HttpURLConnection)url.openConnection();
byte[] authData = Base64.encode((username + password).getBytes());
connection.setRequestMethod("POST");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestProperty("Authorization", "Basic " + new String(authData));
connection.setRequestProperty("Content-Length", String.valueOf(authData.length));
try (DataOutputStream writer = new DataOutputStream(connection.getOutputStream())) {
writer.writeBytes("REPLACE ME WITH DATA TO BE WRITTEN");
writer.flush();
}
try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
String data = null;
while ((data = reader.readLine()) != null) {
jsonString.append(data);
}
}
} catch (IOException ex) {
//Handle exception.
} finally {
if (connection != null)
connection.disconnect();
}
return jsonString.toString();
}
You should send empty data in body if you are using post method.
For example if you are using json data you need to send "{}"
public void Post() throws Exception {
StringBuffer d = new StringBuffer();
String da = "ClearanceDate=2020-08-31&DepositeDate=2020-08-31&BankTransactionNo=UATRYU56789";
URL url = new URL("https://abcd/AddReceipt?" + da);
byte[] postDataBytes = ("https://abcd/AddReceipt?" + da).toString()
.getBytes("UTF-8");
System.out.println("Data--" + postDataBytes);
HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
// con.setRequestProperty("User-Agent",
// "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11");
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
con.setRequestProperty("Content-Length",
String.valueOf(postDataBytes.length));
con.setRequestProperty(
"Authorization",
"Bearer "
+ "o731WGgp1d913ZOYivnc55yOg0y1Wk7GsT_mnCUKOJf1VChYOdfRjovAxOhyyPKU93ERue6-l9DyG3IP29ObsCNTFr4lGZOcYAaR96ZudKgWif1UuSfVx4AlATiOs9shQsGgb1oXN_w0NRJKvYqD0LLsZLstBAzP1s5PZoaS9c6MmO32AV47FUvxRT6Tflus5DBDHji3N4f1AM0dShbzmjkBCzXmGzEDnU6Jg1Mo5kb884kParngKADG5umtuGbNzChQpMw_A0SyEYaUNh18pXVmnNhqM3Qx5ZINwDEXlYY");
con.setRequestProperty("Accept", "application/json");
con.setDoInput(true);
con.setDoOutput(true);
con.getOutputStream().write(postDataBytes);
int status = con.getResponseCode();
System.out.println("Response status: " + status + "|"
+ con.getResponseMessage());
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String inputLine;
StringBuffer content = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
in.close();
con.disconnect();
System.out.println("Response status: " + status);
System.out.println(content.toString());
System.out.print("Raw Response->>" + d);
}

Error 86 This method requires a GET or HEAD using Bearer token on Twitter Rest API 1.1 using Java in AppEngine

I have my bearerToken and userID as per Twitter instructions https://dev.twitter.com/docs/auth/application-only-auth and I want t get a list of followers.
I'm getting error 86, which isn't on the list of error codes https://dev.twitter.com/docs/error-codes-responses
Any pointers would be appreciated.
public String getTwitterFriends(String userID, String bearerToken) {
// Use App Bearer token to get public friends
String answer = "";
String param = "count=5000&cursor=-1&user_id=" + userID;
HttpURLConnection connection = null;
try {
// String request =
// "https://api.twitter.com:443/1.1/friends/ids.json?" + param;
String request = "https://api.twitter.com/1.1/friends/ids.json?"
+ param;
URL url = new URL(request);
connection = (HttpURLConnection) url.openConnection();
System.setProperty("http.keepAlive", false ? "true" : "false");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("GET");
// connection.setRequestProperty("Host", "api.twitter.com" +
// ":443");
connection.setRequestProperty("Host", "api.twitter.com");
connection.setRequestProperty("Accept", "*/*");
connection.setRequestProperty("Authorization", "Bearer "
+ bearerToken);
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded;charset=utf-8");
connection.setRequestProperty("User-Agent", "UnhappyChappy");
// connection.setRequestProperty("Accept-Encoding", "gzip");
// connection.setRequestProperty("Content-Length", "" +
// Integer.toString(param.getBytes().length));
connection.setUseCaches(false);
DataOutputStream wr = new DataOutputStream(
connection.getOutputStream());
// wr.writeBytes(param);
wr.flush();
wr.close();
BufferedReader reader = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String line;
StringBuilder str = new StringBuilder();
while ((line = reader.readLine()) != null) {
System.out.println(line);
str.append(line);
}
reader.close();
connection.disconnect();
answer = str.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(answer);
return answer;
}
It was the way I issued the GET. I had to go to a lower level on App Engine and use FetchOptions This worked for me, hopefully it will help someone else.
URL url = new URL(request);
HTTPRequest req = new HTTPRequest(url, HTTPMethod.GET);
req.addHeader(new HTTPHeader("Authorization", "Bearer " + bearerToken));
HTTPResponse response = URLFetchServiceFactory.getURLFetchService().fetch(req);
System.out.println(new String(response.getContent()));

Logging in on website programmatically

I have used this tutorial to try to login to a website from the company I am doing my internship at: http://www.mkyong.com/java/how-to-automate-login-a-website-java-example/
However, It is not logging in, since the URL when you're logged in to the site is the same as when you're not logged in. So all that happens is me adding the data to the fields, and then the page refreshes, with nothing happening. Can anyone tell me how I am supposed to continue?
Thanks
(Edit): I only have a redirect link
public class ProfileLogin extends AsyncTask<Void, Void, Void>{
private List<String> cookies;
private HttpsURLConnection conn;
private final String USER_AGENT = "Mozilla/5.0";
private String page;
private String userName;
private String passWord;
private String postParams;
URL obj;
//Setting up out connection
public ProfileLogin(String user, String pass){
CookieManager cManager = new CookieManager();
CookieHandler.setDefault(cManager);
page = null;
try {
obj = new URL(LOGIN_URL);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//Setting the username and password
userName = user;
passWord = pass;
try {
conn = (HttpsURLConnection) obj.openConnection();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//Starting our Asynctask to do all of the networking
execute();
}
public VpnProfile getProfiles(){
VpnProfile profile = new VpnProfile(null);
return profile;
}
public String getPageContent() throws Exception{
//Set Get method
conn.setRequestMethod("GET");
conn.setUseCaches(false);
//The properties of our site, we need to 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", "nl-NL,nl;q=0.8,en-US;q=0.6,en;q=0.4");
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 : " + LOGIN_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();
setCookies(conn.getHeaderFields().get("Set-Cookie"));
return response.toString();
}
private String getFormParams(String userName2, String passWord2) throws Exception{
System.out.println("Extract form's data...");
Document doc = Jsoup.parse(page);
//Elements of the login page
Element userNameElement = doc.getElementById("username");
Element passWElement = doc.getElementById("password");
List<String> paramList = new ArrayList<String>();
paramList.add(userNameElement.attr("name") + "=" + URLEncoder.encode(userName2, "UTF-8"));
paramList.add(passWElement.attr("name") + "=" + URLEncoder.encode(passWord2, "UTF-8"));
StringBuilder result = new StringBuilder();
for(String param : paramList){
if(result.length() == 0){
result.append(param);
} else {
result.append("&" + param);
}
}
return result.toString();
}
private void sendPost(String postParams) throws Exception {
conn = (HttpsURLConnection) obj.openConnection();
//Act like a browser
conn.setUseCaches(false);
conn.setRequestMethod("POST");
//This line is deleted, I can't show the url, I set the host here
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", "nl-NL,nl;q=0.8,en-US;q=0.6,en;q=0.4");
if(cookies != null){
for(String cookie : this.cookies){
System.out.println("This is cookies: " + cookie);
conn.addRequestProperty("cookie", cookie.split(";", 1)[0]);
}
}
conn.setRequestProperty("Connection", "keep-alive");
//Deleted line setting referer URL
conn.setRequestProperty("Content-Type", "text/html; charset=UTF-8");
conn.setRequestProperty("Content-Length", Integer.toString(postParams.length()));
conn.setDoOutput(true);
conn.setDoInput(true);
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 : " + LOGIN_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();
}
#Override
protected Void doInBackground(Void... arg0) {
try {
page = getPageContent();
postParams = getFormParams(userName, passWord);
sendPost(postParams);
page = getPageContent();
Document doc = Jsoup.parse(page);
Element userNameElement = doc.getElementById("username");
if(userNameElement.toString() != null){
System.out.println("Not logged in");
}else{
System.out.println("Logged in!");
}
}catch(Exception e){
e.printStackTrace();
}
return null;
}
private void setCookies(List<String> cookies) {
this.cookies = cookies;
}
}
I kind of found a way around: How to log into Facebook programmatically using Java?
This works really well for me and gives me really clean and short code :)

Categories