How to call subsequent request using j_security_check - java

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.

Related

Malformed request exception when trying to send GET request

I'm trying to connect to GDAX using their REST API.
I first want to do something very simple, i.e. getting historic rates.
I tried this:
private static final String GDAX_URL = "https://api.gdax.com";
public String getCandles(final String productId, final int granularity) {
HttpsURLConnection connection = null;
String path = "/products/" + productId + "/candles";
try {
//Create connection
URL url = new URL(GDAX_URL);
connection = (HttpsURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("granularity", String.valueOf(granularity));
connection.setUseCaches(false);
connection.setDoOutput(true);
//Send request
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
wr.writeBytes(path);
wr.close();
//Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
StringBuffer response = new StringBuffer();
String line;
while ((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
System.out.println(response.toString());
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (connection != null) {
connection.disconnect();
}
}
return null;
}
But I get a 400 code in return "Bad Request – Invalid request format".
My problem is with the passing of the path "/products//candles" and the parameters (e.g. granularity).
I don't understand what should go in the request properties and in the message itself, and in what form.
I managed to make it work like this:
URL url = new URL(GDAX_URL + path + "?granularity="+granularity);
connection = (HttpsURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Content-Type", "application/json");
Not sure how to use the DataOutputStream, so I just removed it. At least it works.

Log in to facebook using httpurlconnection

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.

Connection timed out only for wikmedia api on server but works on local

Following piece of code was working for the last three years, but all of a sudden it throws connection timed out only in server, but works as intended in localhost.
Any comments ?
public String getWikiContent(String query) {
StringBuilder builder = new StringBuilder();
String path = "https://en.wikipedia.org/w/api.php?action=query&prop=extracts&exintro=1&explaintext=1&titles=" + query + "&format=json&redirects";
try {
URL url = new URL(path);
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
urlConn.setRequestProperty("Content-Type",
"application/json");
if (urlConn.getResponseCode() != 200) {
throw new IOException(urlConn.getResponseMessage());
}
InputStream is = urlConn.getInputStream();
BufferedReader buff = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = buff.readLine()) != null) {
builder.append(line);
}
}catch (IOException e){
e.printStackTrace();
}
return builder.toString();
}
For some reasons its a network issue, just adding a proxy server fixed it.
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(url,port));
URLConnection urlConn = url.openConnection(proxy);

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()));

Sending post request to https

I need to send a post request to a https address. I have a function that sends post messages currectly but i cant seem to make it work for https.
public static String serverCall(String link, String data){
HttpURLConnection connection;
OutputStreamWriter request = null;
URL url = null;
String response = null;
String parameters = data;
try
{
url = new URL(link);
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "text/xml");
connection.setRequestMethod("POST");
request = new OutputStreamWriter(connection.getOutputStream());
request.write(parameters);
request.flush();
request.close();
String line = "";
InputStreamReader isr = new InputStreamReader(connection.getInputStream());
BufferedReader reader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
// Response from server after process will be stored in response variable.
response = sb.toString();
isr.close();
reader.close();
}
catch(IOException e)
{
// Error
}
return response;
}
i have tryed using HttpsURLConnection insted of HttpURLConnection, i am still getting null from my server.
you should call connect();
....
connection.setRequestMethod("POST");
connection.connect();
....

Categories