I am learning java. I've tried to access a website and see how many characters are there. A website I tried is:
http://cs.armstrong.edu/liang/data/Lincoln.txt
I get a I/O error: no such file output. but I shouldn't get since the web site is up & running.
package ikinciHaftam;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Scanner;
public class ReadFileFromURL {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.print("Enter a URL: ");
Scanner inURL = new Scanner(System.in);
String URLString = inURL.next();
inURL.close();
try{
URL url = new URL(URLString);
int count =0;
Scanner input = new Scanner(url.openStream());
System.out.println(url.openStream());
while (input.hasNext()){
String line = input.nextLine();
count += line.length();
}
System.out.println("The file size is " + count + " characters");
input.close();
}
catch(MalformedURLException ex){
System.out.println("Malformed url");
}
catch(IOException e){
e.printStackTrace();
}
}
}
and I get:
java.net.UnknownHostException: cs.armstrong.edu
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at sun.net.NetworkClient.doConnect(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient.<init>(Unknown Source)
at sun.net.www.http.HttpClient.New(Unknown Source)
at sun.net.www.http.HttpClient.New(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect0(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.connect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at java.net.URL.openStream(Unknown Source)
at ikinciHaftam.ReadFileFromURL.main(ReadFileFromURL.java:18)
Related
I am creating an article summarization project however I am a beginner in java and cannot fix the error. What I am trying to do is get the URL's from Bing search API for custom query which I can later summarize.
package Summarizer;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Scanner;
import org.core4j.Enumerable;
import org.odata4j.consumer.ODataConsumer;
import org.odata4j.consumer.ODataConsumers;
import org.odata4j.consumer.behaviors.OClientBehaviors;
import org.odata4j.core.OEntity;
import org.odata4j.core.OQueryRequest;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* #author Safer
*/
public class Crawler {
ArrayList<String> links = new ArrayList<String>();
String qry;
int count = 10;
public Crawler(String qry) {
this.qry = qry;
getURL();
printToFile();
}
public Crawler(String qry, int count) {
this.qry = qry;
this.count = count;
getURL();
printToFile();
}
public static void main(String[] args) {
Crawler crawller = new Crawler("paris attack");
crawller.getURL();
crawller.printToFile();
}
public void getURL() {
qry = "\'" + qry + "\'";
//System.setProperty("https.proxyHost", "172.31.1.4");
//System.setProperty("https.proxyPort", "8080");
ODataConsumer c = ODataConsumers.newBuilder("https://api.datamarket.azure.com/Bing/Search").setClientBehaviors(OClientBehaviors.basicAuth("accountKey", "I/JMZMShDneSQBg6o+21hcz5eEjR4ROyxnFwG1K4iRM")).build();
OQueryRequest<OEntity> oRequest = c.getEntities("Web").custom("Query", qry);
Enumerable<OEntity> entities = oRequest.execute();
Iterator i = entities.iterator();
while (i.hasNext() && count > 0) {
String[] fields = i.next().toString().split("OProperty");
String link = fields[fields.length - 1].split(",")[2];
links.add(link.substring(0, link.length() - 2));
System.out.println(link.substring(0, link.length() - 2));
count --;
}
}
public void printToFile() {
System.out.println(links.size());
try {
PrintWriter out = new PrintWriter("URL\\urlfile.txt");
for (int i = 0 ; i < links.size() ; i ++) {
out.println(links.get(i));
}
out.close();
}catch(Exception ex){}
}
}
i expect the output to generate the summary of the links from bing search api but couldn't fetch the url
and i am getting this kinda error
Exception in thread "AWT-EventQueue-0" com.sun.jersey.api.client.ClientHandlerException: java.net.ConnectException: Connection timed out: connect
at com.sun.jersey.client.urlconnection.URLConnectionClientHandler.handle(URLConnectionClientHandler.java:128)
at com.sun.jersey.api.client.Client.handle(Client.java:457)
at com.sun.jersey.api.client.WebResource.handle(WebResource.java:557)
at com.sun.jersey.api.client.WebResource.access$300(WebResource.java:69)
at com.sun.jersey.api.client.WebResource$Builder.method(WebResource.java:539)
at org.odata4j.jersey.consumer.ODataJerseyClient.doRequest(ODataJerseyClient.java:143)
at org.odata4j.consumer.AbstractODataClient.getMetadata(AbstractODataClient.java:43)
at org.odata4j.consumer.AbstractODataConsumer$CachedEdmDataServices.refreshDelegate(AbstractODataConsumer.java:212)
at org.odata4j.consumer.AbstractODataConsumer$CachedEdmDataServices.getDelegate(AbstractODataConsumer.java:205)
at org.odata4j.internal.EdmDataServicesDecorator.findEdmEntitySet(EdmDataServicesDecorator.java:46)
at org.odata4j.consumer.AbstractODataConsumer$CachedEdmDataServices.findEdmEntitySet(AbstractODataConsumer.java:221)
at org.odata4j.consumer.AbstractODataConsumer.getFeedCustomizationMapping(AbstractODataConsumer.java:235)
at org.odata4j.consumer.AbstractODataConsumer.getEntities(AbstractODataConsumer.java:73)
at org.odata4j.consumer.AbstractODataConsumer.getEntities(AbstractODataConsumer.java:69)
at Summarizer.Crawler.getURL(Crawler.java:51)
at Summarizer.Crawler.<init>(Crawler.java:37)
at Summarizer.Summary.<init>(Summary.java:30)
at GUI.Base.jButton3ActionPerformed(Base.java:344)
at GUI.Base.access$3(Base.java:331)
at GUI.Base$4.actionPerformed(Base.java:135)
at java.desktop/javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at java.desktop/javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at java.desktop/javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at java.desktop/javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at java.desktop/javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.desktop/java.awt.Component.processMouseEvent(Unknown Source)
at java.desktop/javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.desktop/java.awt.Component.processEvent(Unknown Source)
at java.desktop/java.awt.Container.processEvent(Unknown Source)
at java.desktop/java.awt.Component.dispatchEventImpl(Unknown Source)
at java.desktop/java.awt.Container.dispatchEventImpl(Unknown Source)
at java.desktop/java.awt.Component.dispatchEvent(Unknown Source)
at java.desktop/java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.desktop/java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.desktop/java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.desktop/java.awt.Container.dispatchEventImpl(Unknown Source)
at java.desktop/java.awt.Window.dispatchEventImpl(Unknown Source)
at java.desktop/java.awt.Component.dispatchEvent(Unknown Source)
at java.desktop/java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.desktop/java.awt.EventQueue.access$600(Unknown Source)
at java.desktop/java.awt.EventQueue$4.run(Unknown Source)
at java.desktop/java.awt.EventQueue$4.run(Unknown Source)
at java.base/java.security.AccessController.doPrivileged(Native Method)
at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.desktop/java.awt.EventQueue$5.run(Unknown Source)
at java.desktop/java.awt.EventQueue$5.run(Unknown Source)
at java.base/java.security.AccessController.doPrivileged(Native Method)
at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.desktop/java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.desktop/java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.desktop/java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.desktop/java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.desktop/java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.desktop/java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.desktop/java.awt.EventDispatchThread.run(Unknown Source)
Caused by: java.net.ConnectException: Connection timed out: connect
at java.base/java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.base/java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.base/java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.base/java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.base/java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.base/java.net.PlainSocketImpl.connect(Unknown Source)
at java.base/java.net.SocksSocketImpl.connect(Unknown Source)
at java.base/java.net.Socket.connect(Unknown Source)
at java.base/sun.security.ssl.SSLSocketImpl.connect(Unknown Source)
at java.base/sun.security.ssl.BaseSSLSocketImpl.connect(Unknown Source)
at java.base/sun.net.NetworkClient.doConnect(Unknown Source)
at java.base/sun.net.www.http.HttpClient.openServer(Unknown Source)
at java.base/sun.net.www.http.HttpClient.openServer(Unknown Source)
at java.base/sun.net.www.protocol.https.HttpsClient.<init>(Unknown Source)
at java.base/sun.net.www.protocol.https.HttpsClient.New(Unknown Source)
at java.base/sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.getNewHttpClient(Unknown Source)
at java.base/sun.net.www.protocol.http.HttpURLConnection.plainConnect0(Unknown Source)
at java.base/sun.net.www.protocol.http.HttpURLConnection.plainConnect(Unknown Source)
at java.base/sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(Unknown Source)
at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream0(Unknown Source)
at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at java.base/java.net.HttpURLConnection.getResponseCode(Unknown Source)
at java.base/sun.net.www.protocol.https.HttpsURLConnectionImpl.getResponseCode(Unknown Source)
at com.sun.jersey.client.urlconnection.URLConnectionClientHandler._invoke(URLConnectionClientHandler.java:215)
at com.sun.jersey.client.urlconnection.URLConnectionClientHandler.handle(URLConnectionClientHandler.java:126)
... 55 more
I'm using Java to check the response of a url I pass in. This is the current code I'm using. However, I keep getting a connection refused error. I'm testing with the basic Google home page so that I know the rough draft of my code works.
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
public class connectTest {
public static void main(String[] args)
{
boolean test = pageExists();
}
public static boolean pageExists(){
int returnCode= 0;
try {
HttpURLConnection.setFollowRedirects(false);
String httpsURL = "https://www.google.com/";
URL testUrl = new URL(httpsURL);
HttpsURLConnection con =
(HttpsURLConnection)testUrl.openConnection();
returnCode= con.getResponseCode();
System.out.println(returnCode);
} catch (Exception e) {
e.printStackTrace();
}
if (returnCode== HttpURLConnection.HTTP_OK){
return true;
}
else if (returnCode== HttpURLConnection.HTTP_BAD_REQUEST || returnCode==
HttpURLConnection.HTTP_NOT_FOUND ){
return false;
}
else
{
System.out.println("The return code was not 200,400 or 404");
return false;
}
}
}
This is the error I get when I run the following:
java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at sun.security.ssl.SSLSocketImpl.connect(Unknown Source)
at sun.security.ssl.BaseSSLSocketImpl.connect(Unknown Source)
at sun.net.NetworkClient.doConnect(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.protocol.https.HttpsClient.<init>(Unknown Source)
at sun.net.www.protocol.https.HttpsClient.New(Unknown Source)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.getNewHttpClient(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect0(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(Unknown Source)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at java.net.HttpURLConnection.getResponseCode(Unknown Source)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getResponseCode(Unknown Source)
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Authenticator;
import java.net.PasswordAuthentication;
import java.net.URL;
public class SaveImageFromUrl {
public static void main(String[] args) throws Exception {
// proxy settings
System.setProperty("http.proxyHost", "porxyHost");
System.setProperty("http.proxyPort", "8080");
Authenticator authenticator = new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return (new PasswordAuthentication("userxyz","password".toCharArray()));
}
};
Authenticator.setDefault(authenticator);
String imageUrl = "https://graph.facebook.com/10000012233xxxx/picture";
String destinationFile = "D://image4.jpg";
saveImage(imageUrl, destinationFile);
}
public static void saveImage(String imageUrl, String destinationFile) throws IOException {
URL url = new URL(imageUrl);
InputStream is = url.openStream();
OutputStream os = new FileOutputStream(destinationFile);
byte[] b = new byte[2048];
int length;
while ((length = is.read(b)) != -1) {
os.write(b, 0, length);
}
is.close();
os.close();
}
}
My code works fine and downloads image for other imageurl paths.But it is not working when I use String imageUrl = "https://graph.facebook.com/10000012233xxxx/picture";
I am getting the following error :
Exception in thread "main" java.net.ConnectException: Connection timed out: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at sun.security.ssl.SSLSocketImpl.connect(Unknown Source)
at sun.security.ssl.BaseSSLSocketImpl.connect(Unknown Source)
at sun.net.NetworkClient.doConnect(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.protocol.https.HttpsClient.<init>(Unknown Source)
at sun.net.www.protocol.https.HttpsClient.New(Unknown Source)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.getNewHttpClient(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(Unknown Source)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(Unknown Source)
at java.net.URL.openStream(Unknown Source)
at SaveImageFromUrl.saveImage(SaveImageFromUrl.java:33)
at SaveImageFromUrl.main(SaveImageFromUrl.java:28)
You need to make sure that your application can follow redirects, because Facebook is sending one if you request
/{user_id}/picture
To implement this, have a look at http://www.mkyong.com/java/java-httpurlconnection-follow-redirect-example/
Also, try setting the Proxy authentication like this:
System.setProperty( "http.proxyUserName", "username" );
System.setProperty( "http.proxyPassword", "password" );
I suspect you get the timeout from your proxy connection, but you should be able to test this yourself.
I am working on a program in Java that requires the user to log in, however when is end the HTTP request and try to read the output it returns HTTP response code 500.
The code in Login.java is as follows:
package net.discfiresoftworks.chat;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
public class Login extends JFrame
{
private static final long serialVersionUID = 1L;
public JTextField user = new JTextField();
public JPasswordField pass = new JPasswordField(20);
public JButton submit = new JButton("Log In");
public JButton create = new JButton("Sign-Up");
public JPanel main = new JPanel();
public JPanel buttons = new JPanel();
public Login()
{
setTitle("DiscFire Account Login");
setSize(350, 180);
setDefaultCloseOperation(3);
setLayout(new FlowLayout(1));
setLocationRelativeTo(null);
setResizable(false);
getContentPane().setBackground(new Color(50, 50, 50));
user.setColumns(20);
pass.setColumns(20);
pass.setBorder(BorderFactory.createCompoundBorder(new EmptyBorder(10, 0, 10, 0), pass.getBorder()));
submit.setBorder(BorderFactory.createLineBorder(Color.GRAY, 1));
create.setBorder(BorderFactory.createLineBorder(Color.GRAY, 1));
submit.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e)
{
String password = new String(pass.getPassword());
sendRequest(user.getText(), password);
}
});
create.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e)
{
}
});
buttons.setLayout(new FlowLayout());
buttons.add(submit);
buttons.add(create);
main.setLayout(new BoxLayout(main, BoxLayout.Y_AXIS));
main.setBorder(BorderFactory.createLineBorder(Color.WHITE, 10));
main.add(user);
main.add(pass);
main.add(buttons);
add(main);
}
public void open()
{
setVisible(true);
}
public void sendRequest(String user, String pass)
{
String output = "";
try
{
String urlParameters = "user=" + URLEncoder.encode(user,"UTF-8") + "&pass=" + URLEncoder.encode(pass,"UTF-8");
URL url = new URL("http://www.discfiresoftworks.net/plogin.php");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("charset", "utf-8");
connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));
connection.setUseCaches(false);
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
System.out.println(urlParameters);
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
output = in.readLine();
in.close();
connection.disconnect();
}catch(Exception e){
e.printStackTrace();
}
String sid = (output.split(":"))[0];
String admin = (output.split(":"))[1];
System.out.println(sid = " " + admin);
}
}
The code in plogin.php is as follows:
<?php
include 'includes/conn.php';
include 'includes/hash.php'
session_start();
if(isset($_POST['user']) && isset($_POST['pass'])){
$user = $_POST['user'];
$password = $_POST['pass'];
if(isset($_POST['redir'])){
$redir = $_POST['redir'];
}else{
$redir = '';
}
$query = $conn->prepare("SELECT Password, Verified, Admin FROM Users WHERE Name=?");
$query->bind_param('s', $user);
if($query->execute()){
$query->bind_result($hash, $ver, $admin);
while($query->fetch()){
if($ver == "T"){
if($query->num_rows > 0){
if(validate_password($password, $hash)){
$_SESSION['user'] = $user;
$msg = session_id() . ':' . $user;
}else{
$msg = 'Incorrect username or password';
}
}else{
$msg = 'Incorrect username or password';
}
}else{
$msg = 'Your account has not been verified, please check your email and do so now if you wish to continue.';
}
}
}else{
$msg = $query->errno . " " . $query->error;
}
}else{
$msg = 'Missing username or password';
}
echo $msg;
?>
Thanks in advance, I hope you can help me :)
Edit: I know it is not a fault in conn.php or hash.php because I have used both of them before and they work fine.
Edit: Stacktrace:
java.io.IOException: Server returned HTTP response code: 500 for URL: http://www.discfiresoftworks.net/plogin.php
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at net.discfiresoftworks.chat.Login.sendRequest(Login.java:116)
at net.discfiresoftworks.chat.Login$1.actionPerformed(Login.java:58)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$200(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 1
at net.discfiresoftworks.chat.Login.sendRequest(Login.java:128)
at net.discfiresoftworks.chat.Login$1.actionPerformed(Login.java:58)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$200(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
I had the same problem and solved now.
Just check for correct encoding. make sure you have encoded everything to the same charset.
in my case I am using ISO8859_1 encoding. the server was responding OK to firefox browser but error500 to my java program. I changed to ISO8859_1 and now it is working:
public void sendPost(String Url, String params) throws Exception {
String url=Url;
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
con.setRequestProperty("Acceptcharset", "en-us");
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
con.setRequestProperty("charset", "EN-US");
con.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
String urlParameters=params;
// Send post request
con.setDoOutput(true);
con.setDoInput(true);
con.connect();
//con.
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + urlParameters);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
System.out.println(response.toString());
this.response=response.toString();
con.disconnect();
}
In the main program I call it like this:
certcon.sendPost("https://www.desphilboy.com/authbox/generateCRT","csr_string="+URLEncoder.encode(requestparams,"ISO8859_1"));
Getting the following exception:-
java.lang.NullPointerException
at com.local.testing.ChatClient$sendButtonActionListener.actionPerformed(ChatClient.java:53)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
I am using the following two classes:-
package com.local.testing;
import java.net.*;
import java.io.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ChatClient {
JTextField outgoing=null;
Socket sock=null;
PrintWriter writer=null;
public void buildGui(){
JFrame frame = new JFrame("ChatClient");
JPanel mainPanel = new JPanel();
outgoing = new JTextField(20);
JButton send = new JButton("send");
send.addActionListener(new sendButtonActionListener());
mainPanel.add(outgoing);
mainPanel.add(send);
frame.getContentPane().add(BorderLayout.CENTER,mainPanel);
frame.setVisible(true);
frame.setSize(400, 400);
frame.pack();
setUpNetworking();
}
private void setUpNetworking(){
try{
sock = new Socket("127.0.0.1",4242);
writer = new PrintWriter(sock.getOutputStream());
System.out.println("Connection Established");
}
catch(UnknownHostException uhe){
uhe.printStackTrace();
}
catch(IOException ioe){
ioe.getMessage();
}
finally{
if(writer !=null){
writer.close();
}
}
}
public class sendButtonActionListener implements ActionListener{
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
//System.out.println(outgoing.getText());
try{
writer.println(outgoing.getText());
writer.flush();
}
catch(Exception e){
e.printStackTrace();
}
outgoing.setText("");
outgoing.requestFocus();
}
}
public static void main(String []x){
ChatClient client = new ChatClient();
client.buildGui();
}
}
package com.local.testing;
import java.io.*;
import java.net.*;
public class ChatServer {
public void connectToClient(){
try {
ServerSocket serverSocket = new ServerSocket(4242);
while(true)
{
Socket sock = serverSocket.accept();
InputStreamReader stream = new InputStreamReader(sock.getInputStream());
BufferedReader reader = new BufferedReader(stream);
String chat=reader.readLine();
System.out.println(chat);
}
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String [] x){
ChatServer server = new ChatServer();
server.connectToClient();
}
}
What could be the issue?
There is something wrong with your setUpNetworking method. If you run the following, you will see that it prints test/test2/null. So you catched the IOException and hence the writer isn't initialized which will throws the NPE :
private void setUpNetworking(){
System.out.println("test");
try{
sock = new Socket("127.0.0.1",4242);
writer = new PrintWriter(sock.getOutputStream());
}
catch(UnknownHostException uhe){
System.out.println("test1");
uhe.printStackTrace();
}
catch(IOException ioe){
System.out.println("test2");
ioe.getMessage();
}
finally{
if(writer !=null){
writer.close();
}
}
System.out.println(writer);
}
If you print the stack trace you get :
java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at com.local.testing.ChatClient.setUpNetworking(ChatClient.java:31)
at com.local.testing.ChatClient.buildGui(ChatClient.java:14)
at com.local.testing.ChatClient.main(ChatClient.java:62)
So you have to fix this error.
It seems that your event handler has be been called before your initialisation in buildGui(). So basically make sure that this function is called earlied e.g. in the constructor.
writer.println(outgoing.getText());
writer is initialized to null and never set to an object before above call.(JTextField outgoing=null;