I have set up a login area on my PHP server. The members.php file requires login; after I login a session is created. The session lasts for a while. I want to make this work so that while the session is still valid the java applet should be able to access members.php page.
I have embedded the Java applet into the members.php page. It makes a HttpURLConnection request, however when I get the response I find that it was redirected by the PHP server to the login page.
How do I set this up correctly?
Here is the Java Applet code:
import java.applet.Applet;
import java.awt.Dimension;
import java.io.BufferedReader;
import java.io.DataInputStream;
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.URLConnection;
import java.util.List;
import java.util.Map;
import javax.swing.JFrame;
import javax.swing.JTextArea;
public class phpConnectApplet extends Applet {
private static final long serialVersionUID = 1L;
public void init() {
URL url = null;
try {
url = new URL("http://www.example.com/members.php");
URLConnection urlConn = url.openConnection();
HttpURLConnection httpConn = (HttpURLConnection) urlConn;
httpConn.setDoOutput(true);
httpConn.setDoInput(true);
httpConn.setUseCaches(false);
httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
DataOutputStream output = new DataOutputStream(httpConn.getOutputStream());
String content = "action=blah"; //just to test the PHP file
output.writeBytes(content);
output.flush();
output.close();
DataInputStream in = new DataInputStream(urlConn.getInputStream());
BufferedReader input = new BufferedReader(new InputStreamReader(in));
String str, result = "";
while ((str = input.readLine()) != null) {
result = result + str + "\n";
}
input.close();
Map<String, List<String>> headers = httpConn.getHeaderFields();
List<String> values = headers.get("Set-Cookie");
String cookieValue = null;
for (String v:values) {
if (cookieValue == null)
cookieValue = v;
else
cookieValue = cookieValue + ";" + v;
}
System.out.println(cookieValue);
JFrame f = new JFrame("App Title");
f.add(new JTextArea(result));
f.setMaximumSize(new Dimension(400,300));
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
} catch (MalformedURLException me) {
me.printStackTrace();
} catch(IOException ie) {
ie.printStackTrace();
} catch(Exception e) {
e.printStackTrace();
}
}
}
The output for this is a JFrame with one JTextField which contains the output HTML of the login page.
You need to capture the value of your PHPSESSID cookie (or whatever you are using for the cookie name) and add it to the request in the HttpURLConnection. This MAY come through as a system parameter, but if not, you can embed the session ID as an applet attribute on the page launching the applet. (I haven't experimented with this part specifically)
Here's a tutorial that explains how to send cookies in the URLConnection class: http://www.hccp.org/java-net-cookie-how-to.html
Specifically see the section titled Setting a cookie value in a request.
Related
I want to match issues in JIRA with other datasource.
I can use curl:
curl -u myname:mypassword
https://jira.myorganization.com/rest/api/latest/issue/TR-1234
This will return info about the issue, for exampel TR-1234, that I want to check some data for.
In java I want to do the same thing but I get javax.net.ssl.SSLHandShakeException
The program I try to run:
import javax.net.ssl.HttpsURLConnection;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class Main {
public static void main(String[] args) {
URL url = null;
try {
url = new URL("https://jira.myorganization.com/rest/api/latest/issue/TR-1234");
HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
String userpass = "myusername:mypassword";
String basicAuth = "Basic " + new String(Base64.getEncoder().encode(userpass.getBytes()));
con.setRequestProperty ("Authorization", basicAuth);
con.setRequestMethod("GET");
con.setRequestProperty("Accept", "application/json");
System.out.println("Resp="+ con.getResponseCode()+" "+con.getResponseMessage());
String contentType = con.getHeaderField("Content-Type");
BufferedReader br = new BufferedReader(new InputStreamReader(
(con.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
con.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Can I somehow pass userid and password to the URL. The application is a tool and it would be ok to let the user input his name and password.
In the following code, the content of HTML is displayed in the console. What I want to do is how can I just show the content of some part of the HTML, for example the HTML content of stock prices?
import java.io.InputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.Scanner;
public class ShowStock {
public static void main(String[] args) throws IOException {
String urlString;
if(args.length == 1)
urlString = args[0];
else
{
urlString = "https://www.google.com/finance/historical?cid=22144&startdate=Jan+1%2C+2014&enddate=Dec+31%2C+2015&num=30&ei=m-JzVqm2L9fJUaOphsAF";
System.out.println("Reading data from " + urlString );
}
// Open connection
URL u = new URL(urlString);
URLConnection connection = u.openConnection();
// check to make sure the page exists
HttpURLConnection httpConnection = (HttpURLConnection) connection;
int code = httpConnection.getResponseCode();
String message = httpConnection.getResponseMessage();
System.out.println(code + " " + message);
if (code != HttpURLConnection.HTTP_OK)
return;
// Read server response
InputStream instream = connection.getInputStream();
Scanner in = new Scanner(instream);
// display server response to console
while (in.hasNextLine())
{
String input = in.nextLine();
System.out.println(input);
}
}
}
If it is XHTML (html like xml), you can use many xml libraries
If not, use an html parser jsoup, htmlcleaner, ...
see this:
Which HTML Parser is the best?
I'm trying to parse an html document in a webservice. According to google, jsoup seem to be the faster and easier html parser, so I included in my project but I get the exception "Exception: java.lang.reflect.InvocationTargetException Message: java.lang.reflect.InvocationTargetException" I have tried everything, but nothings give results. Please help
I add jsoup.jar in my project's libray classpath.
I am using Eclipse Luna on Windows XP
Java 1.7 apache tomcat 7.0
this is my code:
try {
url = new URL("http://consulta.muniguate.com/emetra/despliega.php?tplaca="+tplaca+"&nplaca="+nplaca);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = rd.readLine()) != null) {
result += line;
}
Document doc = Jsoup.connect(result).get();
String title= doc.title();
System.out.println(title);
rd.close();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
This is the full code:
package clases;
import java.io.BufferedReader;
import javax.jws.WebService;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.InvocationTargetException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import org.jsoup.Connection.Method;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
#WebService(serviceName = "Transito")
public class Transito {
#WebMethod(operationName = "consultar_saldo")
public String consultar_saldo(String tplaca, int nplaca) throws InvocationTargetException {
String result = "";
try {
Document doc= Jsoup.connect("http://www.muniguate.com/utilities/remisiones.htm?tplaca="+tplaca+"&nplaca="+nplaca).userAgent("Mozilla").get();
String result = doc.title();
System.out.println(result);
} catch (Exception e){
e.getCause();
}
return result;
}
}
Jsoup.connect() accepts a url string, not response content
"I have tried everything, but nothings give results."
In that case you are doomed since there is nothing left for us to try.
But lets assume that you didn't try everything. Lets assume that documentation of Jsoup.connect() is actually telling the true, and this method is used only to create Connection to resource which should be parsed, not to parse it. Its get() method job to connect to resource from created Connection, parse it and return it as Document.
So this method instead of HTML text of resource, will need information required for connection like URL.
So instead of manually creating HttpURLConnection and reading its HTML code, pass string representing URL to Jsoup.connect() and then using get() connect and parse to this resource.
So instead of
URL url = new URL("http://consulta.muniguate.com/emetra/despliega.php?tplaca="+tplaca+"&nplaca="+nplaca);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
BufferedReader rd = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
String line = null;
String result = "";
while ((line = rd.readLine()) != null) {
result += line;
}
Simply use
Document doc = Jsoup.connect("http://consulta.muniguate.com/emetra/despliega.php?tplaca="+tplaca+"&nplaca="+nplaca).get();
Now you should be able to use
String title = doc.title();
System.out.println(title);
I am developing a Java application to be the server in a Google Cloud Messaging Android app.
I have been following a tutorial and I managed to do rest of the tutorial with out a trouble.
My Java application has three classes which are Content.java, POST2GCM.java, App.java. These classes do what the name describes.
Content.java class is below.
package com.hmkcode.vo;
import java.io.Serializable;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
public class Content implements Serializable {
private List<String> registration_ids;
private Map<String,String> data;
public void addRegId(String regId){
if(registration_ids == null)
registration_ids = new LinkedList<String>();
registration_ids.add(regId);
}
public void createData(String title, String message){
if(data == null)
data = new HashMap<String,String>();
data.put("title", title);
data.put("message", message);
}
}
App.java class is below
package com.hmkcode.vo;
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 com.fasterxml.jackson.databind.ObjectMapper;
import com.hmkcode.vo.Content;
public class App
{
public static void main( String[] args )
{
System.out.println( "Sending POST to GCM" );
String apiKey = "AIzaSyB8azikXJKi_NjpWcVNJVO0d........";
Content content = createContent();
POST2GCM.post(apiKey, content);
}
public static Content createContent(){
Content c = new Content();
c.addRegId("APA91bFqnQzp0z5IpXWdth1lagGQZw1PTbdBAD13c-UQ0T76BBYVsFrY96MA4SFduBW9RzDguLaad-7l4QWluQcP6zSoX1HSUaAzQYSmI93....");
c.createData("Test Title", "Test Message");
return c;
}
}
POST2GCM.java class is below
package com.hmkcode.vo;
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 com.fasterxml.jackson.databind.*;
public class POST2GCM {
public static void post(String apiKey, Content content){
try{
// 1. URL
URL url = new URL("https://android.googleapis.com/gcm/send");
// 2. Open connection
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 3. Specify POST method
conn.setRequestMethod("POST");
// 4. Set the headers
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Authorization", "key="+apiKey);
conn.setDoOutput(true);
// 5. Add JSON data into POST request body
//`5.1 Use Jackson object mapper to convert Content object into JSON
ObjectMapper mapper = new ObjectMapper();
// 5.2 Get connection output stream
DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
// 5.3 Copy Content "JSON" into
mapper.writeValue(wr,content);
// 5.4 Send the request
wr.flush();
// 5.5 close
wr.close();
// 6. Get the response
int responseCode = conn.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// 7. Print result
System.out.println(response.toString());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
The problem arises in the POST2GCM.java class, in the line
mapper.writeValue(wr,content);
Where the suggestions are to add try catch block,Add exception to method signature, Add catch clauses(s).
I did all the suggestions which did not solve the problem.
What would be the problem here?
You need to add the jackson-core-2.4.3.jar library file to your project.
Add it to your java build path too.
Of course ... 2.4.3 is the version I used, but it should work with previous versions.
I am trying to connect to a secured connection URL (https://example.com ) using a Java program to check availability of the site. Generally, I connect to https://example.com in browser by disabling proxy settings. Also, we have installed certificates in trusted root certificates.
I have added these certificates to Java Keystore successfully.
import java.net.URL;
import java.net.URLConnection;
import java.security.Security.*;
import com.sun.net.ssl.*;
import com.sun.*;
import javax.net.ssl.HttpsURLConnection;
import java.security.cert.Certificate;
import java.io.*;
import javax.net.ssl.SSLPeerUnverifiedException;
import org.omg.CORBA_2_3.portable.InputStream;
public class TestConn {
public static void main(String args [])
{
try{
URL hp = new URL("https://example.com");
HttpsURLConnection hpCon = (HttpsURLConnection)hp.openConnection();
boolean isProxy = hpCon.usingProxy();
System.out.println("is using proxy " + isProxy);
InputStream obj = (InputStream) hpCon.getInputStream();
while(obj.read()!=-1){
System.out.println(obj.read_char());
}
System.out.println("content >> " + obj.toString());
}catch (Exception ex){
ex.printStackTrace();
}
}
}
I have encountered the following error:
java.net.ProtocolException: Server redirected too many times (20)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(Unknown Source)
at TestConn.main(TestConn.java:28)
Can anyone please help me regarding this exception?
If you want to check availability of the site, you should use hpCon.getResponseCode();.
Response code 200 means that site is available. Frankly, i don't know your further purpose.
This is the modified codes, sure got the output content.
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
public class Test {
public static void main(String[] args) {
try {
URL hp = new URL("https://godaddy.com");
HttpsURLConnection hpCon = (HttpsURLConnection) hp.openConnection();
boolean isProxy = hpCon.usingProxy();
System.out.println("is using proxy " + isProxy);
InputStream obj = hpCon.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(obj));
String s;
while ((s = br.readLine()) != null) {
System.out.println("content >>" + s);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}