Search Tweets with pure Java 400 get Bad Request - java

I tried use search tweets use twitter search api.
But when i get bearer token then send request to
/1.1/search/tweets.json?count=2
Its response is 400 (Bad Request)
I don't know how is wrong... Anyone can help me ??
Here is my Code all from http://www.coderslexicon.com/demo-of-twitter-application-only-oauth-authentication-using-java/
I also watch Application-only authentication but still don't know why.
Hope someone can tell me ....
private final static String getTokenURL = "https://api.twitter.com/oauth2/token";
private static String bearerToken;
static final String ACCESS_TOKEN = "1111111112-H************************************s";
static final String ACCESS_SECRET = "S************************************n";
static final String CONSUMER_KEY = "q************************************g";
static final String CONSUMER_SECRET = "Q************************************a";
public static void main(String[] args) {
new Thread(new Runnable() {
#Override
public void run() {
try {
bearerToken = requestBearerToken(getTokenURL);
searchTweets("https://api.twitter.com/1.1/search/tweets.json?count=2");
} catch (IOException e) {
System.out.println("IOException e");
e.printStackTrace();
}
}
}).start();
}
private static String encodeKeys(String consumerKey, String consumerSecret) {
try {
String encodedConsumerKey = URLEncoder.encode(consumerKey, "UTF-8");
String encodedConsumerSecret = URLEncoder.encode(consumerSecret,
"UTF-8");
String fullKey = encodedConsumerKey + ":" + encodedConsumerSecret;
byte[] encodedBytes = Base64.encodeBase64(fullKey.getBytes());
return new String(encodedBytes);
} catch (UnsupportedEncodingException e) {
return new String();
}
}
private static String requestBearerToken(String endPointUrl)
throws IOException {
HttpsURLConnection connection = null;
String encodedCredentials = encodeKeys(CONSUMER_KEY, CONSUMER_SECRET);
try {
URL url = new URL(endPointUrl);
connection = (HttpsURLConnection) url.openConnection();
System.out.println(connection);
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Host", "api.twitter.com");
connection.setRequestProperty("User-Agent", "MwTestTwitterAPI");
connection.setRequestProperty("Authorization", "Basic "
+ encodedCredentials);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
connection.setRequestProperty("Content-Length", "29");
connection.setUseCaches(false);
writeRequest(connection, "grant_type=client_credentials");
System.out.println(connection.getResponseCode());
System.out.println(connection.getResponseMessage());
String result = readResponse(connection);
JSONObject jsonResult=new JSONObject(result);
if (jsonResult.get("token_type") != null && jsonResult.get("token_type").equals("bearer") ) {
return jsonResult.getString("access_token");
}
return new String();
} catch (MalformedURLException | JSONException e) {
throw new IOException("Invalid endpoint URL specified.", e);
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
private static String searchTweets(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", "MwTestTwitterAPI");
connection.setRequestProperty("Authorization", "Bearer " + bearerToken);
connection.setUseCaches(false);
String result = readResponse(connection);
System.out.println("fetchTimelineTweet---result:"+result);
if (result != null || result.equals("")) {
return result;
}
return new String();
}
catch (MalformedURLException e) {
throw new IOException("Invalid endpoint URL specified.", e);
}
finally {
if (connection != null) {
connection.disconnect();
}
}
}
// Writes a request to a connection
private static boolean writeRequest(HttpURLConnection connection,
String textBody) {
try {
BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(
connection.getOutputStream()));
wr.write(textBody);
wr.flush();
wr.close();
return true;
} catch (IOException e) {
return false;
}
}
// Reads a response for a given connection and returns it as a string.
private static String readResponse(HttpURLConnection connection) {
try {
StringBuilder str = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String line = "";
while ((line = br.readLine()) != null) {
str.append(line + System.getProperty("line.separator"));
}
return str.toString();
} catch (IOException e) {
return new String();
}
}

You're missing a query variable q, which is a required parameter.
Try changing your request url to: https://api.twitter.com/1.1/search/tweets.json?count=2&q=test

Related

Twitter fetching application only bearer token HTTP 403 Forbidden

I am trying to fetch the application only bearer token by using my consumer key and consumer secret following this. This is my implementation:
public class OAuthApplicationOnlyBearerTokenFetchTask extends AsyncTask<String, Void, String> {
private static Logger logger =
Logger.getLogger(OAuthApplicationOnlyBearerTokenFetchTask.class.getName());
final static String URL_TWITTER_OAUTH2_TOKEN = "https://api.twitter.com/oauth2/token";
final static String USER_AGENT = "TwitterMotion User Agent";
protected String mApplicationOnlyBearerToken;
#Override
protected String doInBackground(String... tokens) {
String consumerKey = tokens[0];
String consumerSecret = tokens[0];
String encodedCredentials = encodeKeysFrom(consumerKey, consumerSecret);
HttpURLConnection urlConnection = null;
try {
URL url = new URL(URL_TWITTER_OAUTH2_TOKEN);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Host", "api.twitter.com");
urlConnection.setRequestProperty("User-Agent", USER_AGENT);
urlConnection.setRequestProperty("Authorization", "Basic " + encodedCredentials);
urlConnection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded;charset=UTF-8");
urlConnection.setRequestProperty("Content-Length", "29");
urlConnection.setUseCaches(false);
writeRequest(urlConnection, "grant_type=client_credentials");
String jsonResponse = readResponse(urlConnection);
logger.log(INFO, "jsonResponse of the bearer oauth request: ", jsonResponse);
if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_FORBIDDEN) {
logger.log(Level.SEVERE, "HTTP 403 (Forbidden) returned from Twitter API call for bearer token. " +
"Check values of Consumer Key and Consumer Secret in tokens.properties");
throw new RejectedAuthorizationException(urlConnection.getResponseCode(), "HTTP 403 (Forbidden) returned attempting to get Twitter API bearer token");
}
JSONObject jsonResponseObject = new JSONObject(jsonResponse);
if (jsonResponseObject != null) {
mApplicationOnlyBearerToken = (String) jsonResponseObject.get("access_token");
} else {
// TODO
}
return mApplicationOnlyBearerToken;
} catch (Exception ex) {
logger.log(Level.SEVERE, "", ex);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return null;
}
#Override
protected void onPostExecute(String applicationOnlyBearerToken) {
this.mApplicationOnlyBearerToken = applicationOnlyBearerToken;
}
public String getApplicationOnlyBearerToken() {
return mApplicationOnlyBearerToken;
}
private String encodeKeysFrom(String consumerKey, String consumerSecret) {
try {
String encodedConsumerKey = URLEncoder.encode(consumerKey, "UTF-8");
String encodedConsumerSecret = URLEncoder.encode(consumerSecret, "UTF-8");
String combinedEncodedKey = encodedConsumerKey + ":" + encodedConsumerSecret;
byte[] encodedBytes = Base64.encode(combinedEncodedKey.getBytes(), Base64.NO_WRAP);
return new String(encodedBytes);
}
catch (UnsupportedEncodingException e) {
// TODO
return null;
}
}
private boolean writeRequest(HttpURLConnection connection, String requestBody)
throws IOException {
BufferedWriter bufferedWriter = null;
try {
bufferedWriter = new BufferedWriter(
new OutputStreamWriter(connection.getOutputStream()));
bufferedWriter.write(requestBody);
bufferedWriter.flush();
return true;
}
catch (IOException ex) {
return false;
}
finally {
if (bufferedWriter != null) {
bufferedWriter.close();
}
}
}
private String readResponse(HttpURLConnection connection) throws IOException {
BufferedReader bufferedReader = null;
try {
StringBuilder stringBuilder = new StringBuilder();
bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line + System.getProperty("line.separator"));
}
return stringBuilder.toString();
}
catch (IOException e) {
return null;
}
finally {
if (bufferedReader != null) {
bufferedReader.close();
}
}
}
}
But I am getting HTTP 403 Forbidden.
I also added permission on manifest file:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
I can not understand what is the issue actually. Thanks in advance!
Never mind, I've found the bug.
String consumerKey = tokens[0];
String consumerSecret = tokens[0];
It should be
String consumerSecret = tokens[1];

Android: java.net.ProtocolException: Unexpected status line: HTTP/1.2 200 OK

I have been working on the following code for a while.
the code worked for the 5.x version of my app but I can't get the code to work for Android version 6.x and higher.
public class PostAsync extends AsyncTask<String, Integer, Double> {
private Context _context = null;
public PostAsync(Context context) {
_context = context;
}
#Override
protected Double doInBackground(String... params) {
String serverResponse = postData(params[0]);
try {
JSONObject obj = new JSONObject(serverResponse);
String id = "";
JSONObject locationobj = obj.getJSONObject("X");
JSONObject response = locationobj.getJSONObject("Y");
id = response.getString("id");
Settings.idcode = id;
// Convert , to %2c, since we're working with a URI here
String number = Settings.number + Settings.code + "," + Settings.idcode; // %2c
_context.startActivity(new Intent(Intent.ACTION_CALL).setData(Uri.parse("tel://" + number)));
}
catch (Exception e) {
// TODO: Errorhandler
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Double result) {
}
protected void onProgressUpdate(Integer... progress) {
}
// Send a POST request to specified url in Settings class, with defined JSONObject message
public String postData(String msg) {
String result = null;
StringBuffer sb = new StringBuffer();
InputStream is = null;
try {
URL url = new URL(Settings.webURL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setChunkedStreamingMode(0);
connection.setReadTimeout(15000);
connection.setConnectTimeout(15000);
connection.setRequestProperty("Content-Encoding", "identity");
connection.setRequestProperty("Accept-Encoding", "identity");
connection.setRequestProperty("User-Agent", "Mozilla/5.0");
connection.setRequestProperty("TYPE", "JSON");
connection.setRequestProperty("KEY", "key");
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
wr.writeBytes(msg);
wr.flush();
wr.close();
int responseCode = connection.getResponseCode();
String responseMessage = connection.getResponseMessage();
System.out.println("Response code: " + responseCode);
System.out.println("Response message: " + responseMessage);
if(responseCode == HttpURLConnection.HTTP_OK){
is = new BufferedInputStream(connection.getInputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String inputLine = "";
try {
while ((inputLine = br.readLine()) != null) {
sb.append(inputLine);
}
result = sb.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
}
I get the following error
java.net.ProtocolException: Unexpected status line: HTTP/1.2 200 OK
Can someone tell me what I am missing?

How can i connect to my MySQL database with an android app?

i am trying to do an android app to write some datas on MySQL database but it does not work i did a Java class for this and i think the problem comes from this. Here is my code :
public class BackgroundTask extends AsyncTask<String, Void, String> {
Context ctx;
BackgroundTask(Context ctx) {this.ctx = ctx;}
#Override
protected String doInBackground(String... params) {
String reg_url = "http://localhost:8080/project/register.php";
String method = params[0];
if (method.equals("register")) {
String name = params[1];
String password = params[2];
String contact = params[3];
String country = params[4];
try {
URL url = new URL(reg_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
OutputStream os = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
String data = URLEncoder.encode("name", "UTF-8") + "=" + URLEncoder.encode(name, "UTF-8") + "&" +
URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8") + "&" +
URLEncoder.encode("contact", "UTF-8") + "=" + URLEncoder.encode(contact, "UTF-8") + "&" +
URLEncoder.encode("country", "UTF-8") + "=" + URLEncoder.encode(country, "UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
os.close();
InputStream IS = httpURLConnection.getInputStream();
IS.close();
return "Registration success";
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(ctx, result, Toast.LENGTH_LONG).show();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
Actually what i would like is to save name, password, contact and country in my database. The problem is this : "Registration success" is never returned it is always null. But i don't know why. When i try to compile it looks like there is no errors and i can see the app.
Thank you very much for your help !
Edit : This is the register.php :
<?php
require "init.php";
$u_name=$_POST["name"];
$u_password=$_POST["password"];
$u_contact=$_POST["contact"]";
$u_country=$_POST["country"];
$sql_query="insert into users values('$u_name', '$u_password', '$u_contact', '$u_country');";
//mysqli_query($connection, $sql_query));
if(mysqli_query($connection,$sql_query))
{
//echo "data inserted";
}
else{
//echo "error";
}
?>
And also the init.php :
<?php
$db_name = "project";
$mysql_user = "root";
$server_name = "localhost";
$connection = mysqli_connect($server_name, $mysql_user, "", $db_name);
if(!$connection){
echo "Connection not successful";
}
else{
echo "Connection successful";
}
?>
Thank you for your help !
My class PutUtility for getData(), PostData, DeleteData(). you just need to change package name
package fourever.amaze.mics;
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.net.URLConnection;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
public class PutUtility {
private Map<String, String> params = new HashMap<>();
private static HttpURLConnection httpConnection;
private static BufferedReader reader;
private static String Content;
private StringBuffer sb1;
private StringBuffer response;
public void setParams(Map<String, String> params) {
this.params = params;
}
public void setParam(String key, String value) {
params.put(key, value);
}
public String getData(String Url) {
StringBuilder sb = new StringBuilder();
try {
// Defined URL where to send data
URL url = new URL(Url);
URLConnection conn = null;
conn = url.openConnection();
// Send POST data request
httpConnection = (HttpURLConnection) conn;
httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpConnection.setRequestMethod("GET");
BufferedReader in = new BufferedReader(
new InputStreamReader(httpConnection.getInputStream()));
String inputLine;
response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (Exception ex) { }
}
return response.toString();
}
public String postData(String Url) {
StringBuilder sb = new StringBuilder();
for (String key : params.keySet()) {
String value = null;
value = params.get(key);
if (sb.length() > 0) {
sb.append("&");
}
sb.append(key + "=" + value);
}
try {
// Defined URL where to send data
URL url = new URL(Url);
URLConnection conn = null;
conn = url.openConnection();
// Send POST data request
httpConnection = (HttpURLConnection) conn;
httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpConnection.setRequestMethod("POST");
httpConnection.setDoInput(true);
httpConnection.setDoOutput(true);
OutputStreamWriter wr = null;
wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(sb.toString());
wr.flush();
BufferedReader in = new BufferedReader(
new InputStreamReader(httpConnection.getInputStream()));
String inputLine;
response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (Exception ex) {
}
}
return response.toString();
}
public String putData(String Url) {
StringBuilder sb = new StringBuilder();
for (String key : params.keySet()) {
String value = null;
try {
value = URLEncoder.encode(params.get(key), "UTF-8");
if (value.contains("+"))
value = value.replace("+", "%20");
//return sb.toString();
// Get the server response
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
if (sb.length() > 0) {
sb.append("&");
}
sb.append(key + "=" + value);
}
try {
// Defined URL where to send data
URL url = new URL(Url);
URLConnection conn = null;
conn = url.openConnection();
// Send PUT data request
httpConnection = (HttpURLConnection) conn;
httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpConnection.setRequestMethod("PUT");
httpConnection.setDoInput(true);
httpConnection.setDoOutput(false);
OutputStreamWriter wr = null;
wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(sb.toString());
wr.flush();
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
;
String line = null;
// Read Server Response
while ((line = reader.readLine()) != null) {
// Append server response in string
sb1.append(line + " ");
}
// Append Server Response To Content String
Content = sb.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (Exception ex) {
}
}
// Send PUT data request
return Url;
}
public String deleteData(String Url) {
StringBuilder sb = new StringBuilder();
for (String key : params.keySet()) {
try {
// Defined URL where to send data
URL url = new URL(Url);
URLConnection conn = null;
conn = url.openConnection();
// Send POST data request
httpConnection = (HttpURLConnection) conn;
httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpConnection.setRequestMethod("DELETE");
httpConnection.connect();
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line = null;
// Read Server Response
while ((line = reader.readLine()) != null) {
// Append server response in string
sb1.append(line + " ");
}
// Append Server Response To Content String
Content = sb.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (Exception ex) {
}
}
}
return Url;
}
}
And use this class like this
#Override
protected String doInBackground(String... params) {
res = null;
PutUtility put = new PutUtility();
put.setParam("ueid", params[0]);
put.setParam("firm_no", params[1]);
put.setParam("date_incorporation", params[2]);
put.setParam("business_name", params[3]);
put.setParam("block_no", params[4]);
try {
res = put.postData(
"Api URL here");
Log.v("res", res);
} catch (Exception objEx) {
objEx.printStackTrace();
}
return res;
}
#Override
protected void onPostExecute(String res) {
try {
} catch (Exception objEx) {
mProgressDialog.dismiss();
objEx.printStackTrace();
}
}
Please use this. Hope it helps you in future also.
Check this if this is the problem
$u_contact=$_POST["contact"]"
here is the problem i think so brother. replace with
$u_contact=$_POST["contact"];

Android HttpURLConnection wierd response

I am trying to get response data of a Http request. My code looks like this :
public class Networking {
// private variables
private URL mUrl;
private InputStream mInputStream;
public void Networking() {}
public InputStream setupConnection(String urlString) {
// public variables
int connectionTimeout = 10000; // milliseconds
int readTimeout = 15000; // milliseconds
try {
mUrl = new URL(urlString);
try {
// initialize connection
HttpURLConnection connection = (HttpURLConnection) mUrl.openConnection();
// setup connection
connection.setConnectTimeout(connectionTimeout);
connection.setReadTimeout(readTimeout);
connection.setRequestMethod("GET");
connection.setDoInput(true);
// start the query
try {
connection.connect();
int response = connection.getResponseCode();
if (response == 200) {
// OK
mInputStream = connection.getInputStream();
return mInputStream;
} else if (response == 401) {
// Unauthorized
Log.e("Networking.setupConn...", "unauthorized HttpURL connection");
} else {
// no response code
Log.e("Networking.setupConn...", "could not discern response code");
}
} catch (java.io.IOException e) {
Log.e("Networking.setupConn...", "error connecting");
}
} catch (java.io.IOException e) {
Log.e("Networking.setupConn...", "unable to open HTTP Connection");
}
} catch (java.net.MalformedURLException e) {
Log.e("Networking.setupConn..", "malformed url " + urlString);
}
// if could not get InputStream
return null;
}
public String getStringFromInputStream() {
BufferedReader br = null;
StringBuilder sb = new StringBuilder(5000);
String line;
try {
br = new BufferedReader(new InputStreamReader(mInputStream), 512);
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (java.io.IOException e) {
Log.e("BufferReader(new ..)", e.toString());
return null;
} finally {
if(br != null) {
try {
br.close();
}catch (java.io.IOException e) {
Log.e("br.close", e.toString());
}
}
}
return sb.toString();
}
}
The problem is that the getStringFromInputStream function always returns a string that is 4063 bytes long. ALWAYS! No matter what the url.
I checked, and the (line = br.readLine()) part of the code always returns a string of fixed length of 4063.
I don't understand this. Please help.
This my code which works for me:
public String getDataFromUrl(String httpUrlString)
URL url = new URL(httpUrlString);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
responseCode = urlConnection.getResponseCode();
if (responseCode != HttpStatus.SC_OK) {
return null;
} else { // success
BufferedReader in = null;
StringBuffer str = new StringBuffer();
try {
in = new BufferedReader(new InputStreamReader(
urlConnection.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
str.append(inputLine);
}
} finally {
if (null != in) {
in.close();
}
urlConnection.disconnect();
}
return str.toString();
}
}
In my opinion, it could be helpful for you if you use a library for http request.
I could suggest retrofit or volley.
Besides that, you could just try other methods to get the String from the InputStream, there is an interesting reply for that here
The one that I've used is
BufferedInputStream bis = new BufferedInputStream(inputStream);
ByteArrayOutputStream buf = new ByteArrayOutputStream();
int result = bis.read();
while(result != -1) {
buf.write((byte) result);
result = bis.read();
}
return buf.toString();

login and download a webpage with java and storing cookies

I'm having trouble logging into my schools moodle webpage and downloading the source code,
so far i am able to receive the login page it never actually logs in,
any help would be greatly appreciated i have been stuck with this problem for a couple of weeks now.
The code below is a not my own but a modified version of multiple examples that i have found on the web.
import java.net.*;
import java.io.*;
import java.util.*;
public class LoginByHttpPost
{
private static final String POST_CONTENT_TYPE = "application/x-www-form-urlencoded";
private static final String LOGIN_USER_NAME = "myusername";
private static final String LOGIN_PASSWORD = "mypassword";
private static final String LOGIN_DOMAIN = "students.ltu.edu.au";
private static final String TARGET_URL = "https://www.latrobe.edu.au/lms/login/";
private String page ="";
public static void main (String args[])
{
LoginByHttpPost httpUrlBasicAuthentication = new LoginByHttpPost();
httpUrlBasicAuthentication.httpPostLogin();
}
public void httpPostLogin ()
{
try
{
String urlEncodedContent = preparePostContent(LOGIN_USER_NAME, LOGIN_PASSWORD, LOGIN_DOMAIN);
HttpURLConnection urlConnection = doHttpPost(TARGET_URL, urlEncodedContent);
page = readResponse(urlConnection);
System.out.println("Successfully made the HTPP POST.");
System.out.println("Recevied response is: '/n" + page + "'");
}
catch(IOException ioException)
{
System.out.println("Problems encounterd.");
}
}
private String preparePostContent(String loginUserName, String loginPassword, String loginDomain) throws UnsupportedEncodingException
{
String encodedLoginUserName = URLEncoder.encode(loginUserName, "UTF-8");
String encodedLoginPassword = URLEncoder.encode(loginPassword, "UTF-8");
String encodedLoginDomain = URLEncoder.encode(loginDomain, "UTF-8");
String content = URLEncoder.encode("username=", "UTF-8") + encodedLoginUserName
+ URLEncoder.encode("&password=", "UTF-8") + encodedLoginPassword
+ URLEncoder.encode("&domain=", "UTF-8") + encodedLoginDomain
+ URLEncoder.encode("&Login=", "UTF-8") + URLEncoder.encode("Login", "UTF-8");
return content;
}
public HttpURLConnection doHttpPost(String targetUrl, String content) throws IOException
{
DataOutputStream dataOutputStream = null;
HttpURLConnection conn = null;
String cookieFirst = null;
String cookieValue = null;
String totalCookie = "";
try
{
CookieManager manager = new CookieManager();
manager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
CookieHandler.setDefault(manager);
URL url = new URL(targetUrl);
conn = (HttpURLConnection)url.openConnection();
conn.getContent();
CookieStore cookiejar = manager.getCookieStore();
List<HttpCookie> cookiesList = cookiejar.getCookies();
for(HttpCookie cookiel: cookiesList)
{
totalCookie += cookiel+"; ";
}
totalCookie = totalCookie.substring(0, totalCookie.length()-1);
System.out.println("Total Cookie: " + totalCookie);
}
catch(Exception e)
{
System.out.println("Something went wrong");
}
HttpURLConnection urlConnection = null;
try{
URL url = new URL(targetUrl);
urlConnection = (HttpURLConnection)url.openConnection();
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setUseCaches(true);
urlConnection.setRequestProperty("Content-Type", POST_CONTENT_TYPE);
urlConnection.setRequestProperty("Content-Length", Integer.toString(content.length()));
urlConnection.setInstanceFollowRedirects(true);
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Cookie", totalCookie);
urlConnection.connect();
dataOutputStream = new DataOutputStream(urlConnection.getOutputStream());
dataOutputStream.writeBytes(content);
dataOutputStream.flush();
dataOutputStream.close();
}
catch(IOException ioException)
{
System.out.println("I/O problems while trying to do a HTTP post.");
ioException.printStackTrace();
if (dataOutputStream != null)
{
try
{
dataOutputStream.close();
}
catch(Throwable ignore)
{
}
}
if (urlConnection != null)
{
urlConnection.disconnect();
}
throw ioException;
}
return urlConnection;
}
private String readResponse(HttpURLConnection urlConnection) throws IOException
{
BufferedReader bufferedReader = null;
try
{
bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String responeLine;
StringBuilder response = new StringBuilder();
while ((responeLine = bufferedReader.readLine()) != null)
{
response.append(responeLine + "\n");
}
return response.toString();
}
catch(IOException ioException)
{
System.out.println("Problems while reading the response");
ioException.printStackTrace();
throw ioException;
}
finally
{
if (bufferedReader != null)
{
try
{
bufferedReader.close();
}
catch(Throwable ignore)
{
}
}
}
}
}
To access this web page and log in, you're using a web browser and not a sequance of telnet commands, because it's much easier, right? Then, as a programmer, do the same and use a programmatic web browser rather than a sequence of low-level actions using cookies and URL connections. It will also be much easier.
HtmlUnit is such a programmatic web browser. The end of its Getting started page shows an example of loading a web page and submitting a form. HtmlUnit will handle the submission, cookie handling, encoding, etc. for you.

Categories

Resources