Parsing cookies to client side - java

Trying to access the cookies in my DownloadDemo class (downloads information on a website in a csv file) but can't seem to find the correct method to do so. My code:
import java.io.*;
import java.net.URL;
import javax.servlet.*;
import javax.servlet.http.*;
public class DownloadDemo extends CookieTest
{
public static void main(String[] args)
{
StringBuilder contents = new StringBuilder(4096);
BufferedReader br = null;
try
{ //goes to the given URL
String downloadSite = ((args.length > 0) ? args[0] : "google.com");
// file saved in your workspace
String outputFile = ((args.length > 1) ? args[1] : "test.csv");
URL url = new URL(downloadSite);
InputStream is = url.openConnection().getInputStream();
br = new BufferedReader(new InputStreamReader(is));
PrintStream ps = new PrintStream(new FileOutputStream(outputFile));
String line;
String newline = System.getProperty("line.separator");
while ((line = br.readLine()) != null)
{
contents.append(line).append(newline);
}
ps.println(contents.toString());
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
try { if (br != null) br.close(); } catch(IOException e) { e.printStackTrace(); }
}
}
}
Cookies class:
import java.io.*;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.net.CookieStore;
import java.net.HttpCookie;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import javax.servlet.*;
import javax.servlet.http.*;
public class CookieTest extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
res.setContentType("text/html");
PrintWriter out = res.getWriter();
//Get the current session ID by searching the received cookies.
String cookieid = null;
Cookie[] cookies = req.getCookies();
if (cookies != null)
{
for (int i = 0; i < cookies.length; i++)
{
if (cookies[i].getName().equals("REMOTE_USER"))
{
cookieid = cookies[i].getValue();
break;
}
}
}
System.out.println("Cookie Id--"+cookieid);
//If the session ID wasn't sent, generate one.
//Then be sure to send it to the client with the response.
}
//Gets the cookie
public void getCookieUsingCookieHandler() {
try {
// Instantiate CookieManager;
// make sure to set CookiePolicy
CookieManager manager = new CookieManager();
manager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
CookieHandler.setDefault(manager);
// get content from URLConnection;
// cookies are set by web site
URL url = new URL("https://google.com");
URLConnection connection = url.openConnection();
connection.getContent();
// get cookies from underlying
// CookieStore
CookieStore cookieJar = manager.getCookieStore();
List <HttpCookie> cookies =
cookieJar.getCookies();
for (HttpCookie cookie: cookies) {
System.out.println("CookieHandler retrieved cookie: " + cookie);
}
} catch(Exception e) {
System.out.println("Unable to get cookie using CookieHandler");
e.printStackTrace();
}
}
public void setCookieUsingCookieHandler() {
try {
// instantiate CookieManager
CookieManager manager = new CookieManager();
CookieHandler.setDefault(manager);
CookieStore cookieJar = manager.getCookieStore();
// create cookie
HttpCookie cookie = new HttpCookie("UserName", "John H");
// add cookie to CookieStore for a
// particular URL
URL url = new URL("https://google.com");
cookieJar.add(url.toURI(), cookie);
System.out.println("Added cookie using cookie handler");
} catch(Exception e) {
System.out.println("Unable to set cookie using CookieHandler");
e.printStackTrace();
}
}
}
Reason for why i'm using cookies is that i need to access the users credentials in order to download the information.
Many thanks in advance.

Related

"AADSTS50058: A silent sign-in request was sent but no user is signed in

Use Case :
I have two application :
1) First one is a Spring boot application, we are exposing our rest endpoint from here.
I want to secure my first application using Azure AD when called from second application and I want to do it in a silent way, that is I should not be prompted for username and password when service to service call happens.
#EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private AADAuthenticationFilter aadAuthFilter;
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/home").permitAll();
http.authorizeRequests().antMatchers("/api/**").authenticated();
http.logout().logoutSuccessUrl("/").permitAll();
http.authorizeRequests().anyRequest().permitAll();
http.csrf().disable();
http.addFilterBefore(aadAuthFilter, UsernamePasswordAuthenticationFilter.class);
}
}
#RestController
public class MyRestController{
#RequestMapping(value = "/api/todolist", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<String> addNewTodoItem(#RequestBody TodoItem item) {
item.setID(todoList.size() + 1);
todoList.add(todoList.size(), item);
return new ResponseEntity<>("Entity created", HttpStatus.CREATED);
}
}
2) Second application is calling this Rest service. (Can you consider this as a java client which is just calling our rest service and then doing some processing).
I want to secure my first application using Azure AD when called from second application and I want to do it in a silent way that is we should not be prompted for username and password when service to service call happens
below is the code :
package sample.aad.security;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.LinkedHashMap;
import java.util.Map;
import org.json.JSONObject;
import ch.qos.logback.core.net.SyslogOutputStream;
public class MyClass {
public static void main(String[] args) throws Exception {
URL url = new URL("https://login.microsoftonline.com/{tenantId}/oauth2/token");
Map<String, Object> params = new LinkedHashMap<>();
params.put("grant_type", "client_credentials");
params.put("client_id", "b2846a59-33e9-4046-8c94-795d8087f453");
params.put("client_secret", "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
params.put("resource", APPID);
StringBuilder postData = new StringBuilder();
for (Map.Entry<String, Object> param : params.entrySet()) {
if (postData.length() != 0)
postData.append('&');
postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
postData.append('=');
postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
}
byte[] postDataBytes = postData.toString().getBytes("UTF-8");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");// multipart/form-data
conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
conn.setDoOutput(true);
conn.getOutputStream().write(postDataBytes);
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
String output;
String last = null;
System.out.println("Output from Server .... \n");
while ((output = in.readLine()) != null) {
System.out.println(output);
if (last == null) {
last = output;
} else {
last.concat(output);
}
}
JSONObject jsonObj = new JSONObject(last.toString());
System.out.println(jsonObj.get("access_token"));
System.out.println(jsonObj.get("token_type"));
invokeRestUrlClientStatic(jsonObj.get("token_type") + " " + jsonObj.get("access_token"));
}
public static void invokeRestUrlClientStatic(String accessToken) {
try {
System.out.println("Invoking");
System.out.println(accessToken);
// Call to Rest service from First Application
URL url = new URL(" http://localhost:8080/api/todolist/");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Authorization", accessToken);
String input = "{\"qty\":100,\"name\":\"iPad 4\"}";
OutputStream os = conn.getOutputStream();
os.write(input.getBytes());
os.flush();
if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Note : I dont have any WebUi in either of the application from where user can login.
But I am getting below error :
Caused by: com.microsoft.aad.adal4j.AuthenticationException: {"error_description":"AADSTS50058: A silent sign-in request was sent but no user is signed in.\r\nTrace ID: b27a4ce6-f1ed-4a5c-b28f-6ee16f990400\r\nCorrelation ID: 168e6a13-8cf6-409f-864a-9f190746edfd\r\nTimestamp: 2018-03-17 10:46:35Z","error":"invalid_grant"}
at com.microsoft.aad.adal4j.AdalTokenRequest.executeOAuthRequestAndProcessResponse(AdalTokenRequest.java:107) ~[adal4j-1.2.0.jar:1.2.0]
at com.microsoft.aad.adal4j.AuthenticationContext.acquireTokenCommon(AuthenticationContext.java:816) ~[adal4j-1.2.0.jar:1.2.0]
at com.microsoft.aad.adal4j.AuthenticationContext.access$100(AuthenticationContext.java:64) ~[adal4j-1.2.0.jar:1.2.0]
Am I missing something so that it works.
I have also tried below code (for my second Application): But still getting same error
public static void main(String[] args) throws MalformedURLException, Exception {
String app_id_uri = "APP ID URL";
String authority = "https://login.microsoftonline.com/common/";
String clientId = "b2846a59-33e9-4046-8c94-795d8087f453";
String clientSecret = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
AuthenticationContext context = null;
AuthenticationResult result = null;
ExecutorService service = null;
ClientCredential credential= null;
try {
service = Executors.newFixedThreadPool(1);
context = new AuthenticationContext(authority, true, service);
credential = new ClientCredential(clientId, clientSecret);
Future<AuthenticationResult> future = context.acquireToken(app_id_uri, credential,null);
result = future.get();
} finally {
service.shutdown();
}
String accessToken = null;
if (result == null) {
throw new ServiceUnavailableException("authentication result was null");
} else {
accessToken = result.getAccessToken();
System.out.println("Access Token: " + accessToken);
}
// Call to my rest service using above accessToken
}

Android Http Get Request

I'm a newbie at android development. I'm trying to send a GET request to an URL. I wrote the below code.
public void searchProducts(View v)
{
//String txtSearchTerm = ((EditText)findViewById(R.id.txtsearch)).getText().toString();
//String termCleaned = txtSearchTerm.replace(' ', '+').toString();
AlertDialog alertMessage = new AlertDialog.Builder(this).create();
alertMessage.setTitle("Loading");
alertMessage.setMessage(GET("http://webkarinca.com/sample.json"));
alertMessage.show();
}
public static String GET(String url){
InputStream inputStream = null;
String result = "";
try {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse httpResponse = httpclient.execute(new HttpGet(url));
inputStream = httpResponse.getEntity().getContent();
if(inputStream != null)
{
result = convertInputStreamToString(inputStream);
}
else
{
result = "Did not work!";
}
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
return result;
}
private static String convertInputStreamToString(InputStream inputStream) throws IOException{
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
String line = "";
String result = "";
while((line = bufferedReader.readLine()) != null)
result += line;
inputStream.close();
return result;
}
I already put imports head of the class. There they are
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;
It doesn't work and at the Problems section it shows as a warning
The type HttpGet is deprecated
The type HttpResponse is deprecated
Try this. it worked for me.
first must implement this on build.gradle: app
implementation("com.squareup.okhttp3:okhttp:4.8.0")
then, use this method
String run(String url) throws IOException {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(url)
.build();
try (Response response = client.newCall(request).execute()) {
return response.body().string();
}
}
Finally, call it on onCreate method
run("enter your URL here");
try this
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;
import android.content.Context;
import com.jivebird.settings.CommonMethods;
public class Connecttoget {
public static String callJson(Context context,String urlstring){
String data=null;
try {
URL url = new URL(urlstring);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Starts the query
conn.connect();
InputStream stream = conn.getInputStream();
data = convertStreamToString(stream);
stream.close();
}catch(SocketTimeoutException e){
CommonMethods.createAlert(context, "Sorry, network error", "");
}
catch (Exception e) {
e.printStackTrace();
}
return data;
}
static String convertStreamToString(java.io.InputStream is) {
java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
return s.hasNext() ? s.next() : "";
}
}
Can you try the below code,if it helps.
HttpURLConnection urlConnection = null;
URL url = null;
JSONObject object = null;
InputStream inStream = null;
try {
url = new URL(urlString.toString());
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.connect();
inStream = urlConnection.getInputStream();
BufferedReader bReader = new BufferedReader(new InputStreamReader(inStream));
String temp, response = "";
while ((temp = bReader.readLine()) != null) {
response += temp;
}
object = (JSONObject) new JSONTokener(response).nextValue();
} catch (Exception e) {
this.mException = e;
} finally {
if (inStream != null) {
try {
// this will close the bReader as well
inStream.close();
} catch (IOException ignored) {
}
}
if (urlConnection != null) {
urlConnection.disconnect();
}
}
Try this code. This worked for me.
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
public class ServerTest extends Activity {
private String TAG = "test";
private String url = "http://webkarinca.com/sample.json";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new Download().execute();
}
public class Download extends AsyncTask<Void, Void, String>{
#Override
protected String doInBackground(Void... params) {
String out = null;
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
final HttpParams httpParameters = httpClient.getParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 15000);
HttpConnectionParams.setSoTimeout(httpParameters, 15000);
HttpGet httpPost = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
out = EntityUtils.toString(httpEntity, HTTP.UTF_8);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return out;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Log.e(TAG, result);
}
}
}
Also make sure you have added this to manifest,
<uses-permission android:name="android.permission.INTERNET" />
and also make sure you are connected to the internet.

Java automatic-login to website. Does not work

I want to create a java application that automatically logs into a website and does stuff. I'm testing it on my localhost. I'm actually totally new at this and I'm trying to get the concept from http://www.mkyong.com/java/how-to-automate-login-a-website-java-example/ and modifying the code to actually work for my localhost.
package random;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
public class InternetAutomationPost {
List<String> cookies;
public void setCookies(List<String> cookies) {
this.cookies = cookies;
}
public List<String> getCookies() {
return cookies;
}
private String requestWebPage(String address) {
try {
URL url = new URL(address);
HttpURLConnection con = (HttpURLConnection)url.openConnection();
// Don't use cache. Get a fresh copy.
con.setUseCaches(false);
// Use post or get.
// And default is get.
con.setRequestMethod("GET");
// Mimic a web browser.
con.addRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
con.addRequestProperty("Accept-Encoding", "gzip,deflate,sdch");
con.addRequestProperty("Accept-Language", "en-US,en;q=0.8");
con.addRequestProperty("Connection", "keep-alive");
con.addRequestProperty("User-Agent", "Mozilla/5.0");
if(cookies != null) {
con.addRequestProperty("Cache-Control", "max-age=0");
for (String cookie : this.cookies) {
System.out.print(cookie.split(";", 1)[0]);
con.addRequestProperty("Cookie", cookie.split(";", 1)[0]);
}
}
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while( (inputLine = br.readLine()) != null) {
response.append(inputLine);
}
br.close();
// Get the response cookies
setCookies(con.getHeaderFields().get("Set-Cookie"));
return response.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
private String parsePage(String page) {
Document doc;
try {
doc = Jsoup.parse(page);
Elements form = doc.getElementsByAttributeValue("action", "login.php");
List<String> paramList = new ArrayList<String>();
for(Element loginForm : form) {
System.out.println(loginForm.html());
Elements Input = loginForm.getElementsByTag("input");
for(Element input : Input) {
String name = input.attr("name");
String value = input.attr("value");
if(name.equals("email")) {
value = "admin#admin.com";
} else if(name.equals("password")) {
value = "password";
} else if(name.equals("")) {
continue;
}
paramList.add(name + "=" + URLEncoder.encode(value, "UTF-8"));
}
}
StringBuilder params = new StringBuilder();
for(String values : paramList) {
if(params.length() == 0) {
params.append(values);
} else {
params.append("&" + values);
}
}
System.out.println("Params: " + params);
return params.toString();
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
private void sendPostLogin(String location, String params) {
try {
URL url = new URL(location);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
// Don't use cache. Get a fresh copy.
con.setUseCaches(false);
// Use post or get. We use post this time.
con.setRequestMethod("POST");
// Mimic a web browser.
con.addRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
con.addRequestProperty("Accept-Encoding", "gzip,deflate,sdch");
con.addRequestProperty("Accept-Language", "en-US,en;q=0.8");
con.addRequestProperty("Connection", "keep-alive");
con.addRequestProperty("User-Agent", "Mozilla/5.0");
if(cookies != null) {
con.addRequestProperty("Cache-Control", "max-age=0");
for (String cookie : this.cookies) {
con.addRequestProperty("Cookie", cookie.split(";", 1)[0]);
}
}
con.addRequestProperty("Content-Length", Integer.toString(params.length()));
con.addRequestProperty("Content-Type", "application/x-www-form-urlencoded");
con.addRequestProperty("Host", "localhost");
con.addRequestProperty("Origin", "http://localhost");
con.addRequestProperty("Referrer", "http://localhost/social/index.php");
con.setDoOutput(true);
con.setDoInput(true);
// Write the parameters. Send post request.
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(params);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + params);
System.out.println("Response Code : " + responseCode);
BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while( (inputLine = br.readLine()) != null) {
response.append(inputLine);
}
br.close();
// Get the response cookies
setCookies(con.getHeaderFields().get("Set-Cookie"));
System.out.println(response.toString());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* #param args
*/
public static void main(String[] args) {
InternetAutomationPost object = new InternetAutomationPost();
String page = object.requestWebPage("http://localhost/social");
String params = object.parsePage(page);
object.sendPostLogin("http://localhost/social/index.php", params);
}
}
EDIT:
Found out why it sent HTTP response code: 413.
con.addRequestProperty("Content-Length:", Integer.toString(params.length()));
should have been:
con.addRequestProperty("Content-Length", Integer.toString(params.length()));
There was a stray ':'. I've fixed it now.
BUT, still my code doesn't actually login and I still need help .
I have put my full program here now.
I might be wrong but I'm thinking that the params aren't actually getting written to the con.getOutputStream() in the code here:
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(params);
wr.flush();
wr.close();
You set the Content-Length to Integer.toString(params.length())
My guess would be, that your params written as bytes are longer than the Content-Length and your server receives more bytes than expected.
Try:
con.addRequestProperty("Content-Length:", Integer.toString(params.getBytes("UTF-8").length()));
This depends on your encoding obviously. Also have a look at this.

Communicate between android Application and java

Every body i am new in program world , I am getting a issue,My Request is related to Communication between Android tablet to Desktop PC using JAVA Code.
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class HelloWorldServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public HelloWorldServlet() {
super();
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.println("Hello Android !!!!");
}
}
above code is my servlet code which is running in my local system server (Tomcat 6.0 ) here i am sending message through println and i want to reveive same message in my Android app which is running in another system. Now i am going to post my android code which is running on another system.
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 android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class HttpGetServletActivity3 extends Activity implements
OnClickListener {
Button button;
TextView outputText;
public static final String URL =
"http://192.168.0.2:9999/HttpGetServlet/HelloWorldServlet";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewsById();
button.setOnClickListener(this);
}
private void findViewsById() {
button = (Button) findViewById(R.id.button);
outputText = (TextView) findViewById(R.id.outputTxt);
}
public void onClick(View view) {
GetXMLTask task = new GetXMLTask();
task.execute(new String[] { URL });
}
private class GetXMLTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String output = null;
for (String url : urls) {
output = getOutputFromUrl(url);
}
return output;
}
private String getOutputFromUrl(String url) {
StringBuffer output = new StringBuffer("");
try {
InputStream stream = getHttpConnection(url);
BufferedReader buffer = new BufferedReader(
new InputStreamReader(stream));
String s = "";
while ((s = buffer.readLine()) != null)
output.append(s);
} catch (IOException e1) {
e1.printStackTrace();
}
return output.toString();
}
// Makes HttpURLConnection and returns InputStream
private InputStream getHttpConnection(String urlString)
throws IOException {
InputStream stream = null;
URL url = new URL(urlString);
URLConnection connection = url.openConnection();
try {
HttpURLConnection httpConnection = (HttpURLConnection) connection;
httpConnection.setRequestMethod("GET");
httpConnection.connect();
if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
stream = httpConnection.getInputStream();
}
} catch (Exception ex) {
ex.printStackTrace();
}
return stream;
}
#Override
protected void onPostExecute(String output) {
outputText.setText(output);
}
}}
Here 192.68.0.2 is ip address of system where servlet code is running in my local system (Tomcat6.0 server which has port no 9999) .But it is not working for me.Both the system are in same wifi network Any help is really very appreciated. Thanks in advance to all
try this i will work for you. This is android code
protected Integer doInBackground(String... arg0) {
/** According with the new StrictGuard policy, running long tasks on the Main UI thread is not possible
So creating new thread to create and execute http operations */
new Thread(new Runnable() {
#Override
public void run() {
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("username",un.getText().toString()));
postParameters.add(new BasicNameValuePair("password",pw.getText().toString()));
String response = null;
try {
response = SimpleHttpClient.executeHttpPost("http://XXX.168.1.X:5555/LoginServlet/loginservlet.do", postParameters);
res = response.toString();
System.out.println("response :"+res);
} catch (Exception e) {
// e.printStackTrace();
errorMsg = e.getMessage();
}
}
}).start();
/** Inside the new thread we cannot update the main thread
So updating the main thread outside the new thread */
try {
}catch (Exception e) {
error.setText(e.getMessage());
// e.printStackTrace();
}
return null;
}
Now this is another class for android
public class SimpleHttpClient {
public static String result="";
/** The time it takes for our client to timeout */
public static final int HTTP_TIMEOUT = 30 * 1000; // milliseconds
/** Single instance of our HttpClient */
private static HttpClient mHttpClient;
/**
* Get our single instance of our HttpClient object.
*
* #return an HttpClient object with connection parameters set
*/
private static HttpClient getHttpClient() {
if (mHttpClient == null) {
mHttpClient = new DefaultHttpClient();
final HttpParams params = mHttpClient.getParams();
HttpConnectionParams.setConnectionTimeout(params, HTTP_TIMEOUT);
HttpConnectionParams.setSoTimeout(params, HTTP_TIMEOUT);
ConnManagerParams.setTimeout(params, HTTP_TIMEOUT);
}
return mHttpClient;
}
/**
* Performs an HTTP Post request to the specified url with the
* specified parameters.
*
* #param url The web address to post the request to
* #param postParameters The parameters to send via the request
* #return The result of the request
* #throws Exception
*/
public static String executeHttpPost(String url, ArrayList<NameValuePair> postParameters) throws Exception {
BufferedReader in = null;
try {
HttpClient client = getHttpClient();
HttpPost request = new HttpPost(url);
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
request.setEntity(formEntity);
// String str1= request.setEntity(formEntity);
System.out.println("actual request"+formEntity);
HttpResponse response = client.execute(request);
System.out.println("response in class"+response);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
result = sb.toString();
}catch(Exception e){
e.printStackTrace();
System.out.println("catch");
}
finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}
/**
* Performs an HTTP GET request to the specified url.
*
* #param url The web address to post the request to
* #return The result of the request
* #throws Exception
*/
public static String executeHttpGet(String url) throws Exception {
String result="";
BufferedReader in = null;
try {
HttpClient client = getHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(url));
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
result = sb.toString();
}
catch(Exception e){
e.printStackTrace();
System.out.println("catch2");
}
finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}}
And finally this is servlet code for you
public class LoginServlet extends HttpServlet {
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
String un,pw;
un=request.getParameter("username");
pw=request.getParameter("password");
System.out.println("username :"+un);
System.out.println("password :"+pw);
if(un.equals("") || pw.equals("") ){
out.print("null");
}
else if(un.equalsIgnoreCase("hello") && pw.equals("world"))
{
out.print("success");
}
else{
out.print("failed");
}
System.out.println("after :");
request.getAttribute("USER"+un);
request.getAttribute("PASS"+pw);
RequestDispatcher rd=request.getRequestDispatcher("home.jsp");
rd.forward(request, response);
}catch(Exception e){
System.out.println("inside exception");
e.printStackTrace();
}
finally {
out.close();
}
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
service(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
service(request, response);
}
#Override
public String getServletInfo() {
return "Short description";
}}

Java, Simulating Browser

I am writing a small java program/api to programatically login/ (do a hthp post with login credentials) to this http://web2sms.ke.airtel.com
For me to post, I need parameter(key and value for the login form). When I render the form via browser, the key/name keep changing everytime to but when I fetch the page via java code below the key is always contact f_1.number, therefore meaning the server in my thinking the server is differentiating if a page is fetched from from a browser or not. How can I simulate a browser and get the figures to be rendered by browser?
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
/**
*
* #author Dell
*/
public class AirtelWeb2Sms {
String link = "http://web2sms.ke.airtel.com";
/**
* #param args the command line arguments
*/
private boolean on = false;
public static void main(String[] args) {
new AirtelWeb2Sms();
}
public AirtelWeb2Sms() {
login();
}
private void login(){
Map <String, String> parameters = new HashMap();
try{
URL url = new URL(link);
URLConnection yc = url.openConnection();
BufferedReader in = new BufferedReader(
new InputStreamReader(
yc.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
{
if(inputLine.contains("<div id=\"loginform\">"))
{
on=true;
}
if(on && (inputLine.contains("input")||inputLine.contains("select"))&& inputLine.contains("name")&& inputLine.contains("value")){
// System.out.println(inputLine);
String[] tokens = inputLine.split("\" ");
String key="", value="";
for(String str: tokens){
if(str.contains("name=")){
key=str.substring(str.indexOf("\"")+1);
}
if(str.startsWith("value")){
value=str.substring(str.indexOf("\"")+1);
}
if(key.contains(".number")){
value="+25473DummyNumber";
}
if(key.contains(".passwd")){
value="dymmerPassword";
}
if(key.contains(".language")){
value="en";
}
}
parameters.put(key, value=value.replace(""", "\""));
System.out.println(key+":"+value);
}
if(inputLine.contains("<input type=\"submit\""))
{
on=false;
}
}
doSubmit(link+"index.hei", parameters);
}
catch(Exception ex){
System.out.println(ex.getLocalizedMessage());
}
}
public void doSubmit(String url, Map<String, String> data) throws Exception
{
URL siteUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) siteUrl.openConnection();
conn.setRequestMethod("POST"); conn.setDoOutput(true);
conn.setDoInput(true); DataOutputStream out = new DataOutputStream(conn.getOutputStream());
Set keys = data.keySet();
Iterator keyIter = keys.iterator(); String content = "";
for(int i=0; keyIter.hasNext(); i++) {
Object key = keyIter.next();
if(i!=0) {
content += "&";
}
content += key + "=" +data.get(key);
}
System.out.println(content);
out.writeBytes(content);
out.flush();
out.close();
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line = "";
while((line=in.readLine())!=null) {
System.out.println(line); } in.close();
}
}
Try setting the "User-Agent" HTTP header to some value that a real browser would send. You can check what's your browser's user-agent string by visiting http://whatsmyuseragent.com/.

Categories

Resources