i tried to get view source(html page) from websit
i used whit this code
public static void main(String[] args) {
URL url;
InputStream is = null;
BufferedReader br;
String line;
try {
url = new URL("http://stackoverflow.com/");
is = url.openStream(); // throws an IOException
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (MalformedURLException mue) {
mue.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
try {
if (is != null) is.close();
} catch (IOException ioe) {
// nothing to see here
}
}
}
and when i bring to line "is = url.openStream();
i received exception "java.net.UnknownHostException"
java.net.UnknownHostException: stackoverflow.com
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.plainConnect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.connect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at java.net.URL.openStream(Unknown Source)
at test.main.main(main.java:17)
do you know how i can fix this code
thanks a lot,
Related
I am trying to post some data into the server. I am using a sample url whichis available online. I am not able to proceed further because the line,
DataOutputStream os = new DataOutputStream(con.getOutputStream());, is throwing Connection Refused Exception.
This is the code...
public static void main(String[] args) throws Exception {
try {
URL url = new URL("https://my-json-server.typicode.com/typicode/demo/posts");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setDoOutput(true);
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json");
JSONObject jsonObj = new JSONObject();
jsonObj.put("id", 5);
DataOutputStream os = new DataOutputStream(con.getOutputStream());
os.writeBytes(jsonObj.toString());
os.flush();
BufferedReader br = new BufferedReader(new InputStreamReader((con.getInputStream())));
int responseCode = con.getResponseCode();
String output;
StringBuffer sb = new StringBuffer();
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
sb.append(output);
break;
}
System.out.println("Response Code: "+responseCode);
System.out.println("URL: "+url);
System.out.println("Parameters: "+jsonObj.toString());
System.out.println("Output: "+output.toString());
con.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Below is the Exception..
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.plainConnect(Unknown Source)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(Unknown Source)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getOutputStream(Unknown Source)
at insertData.main(insertData.java:37)
Please help me with this. Thanks.
You need to change your BufferedReader to BufferedInputStream also the "while" loop that you have is constructed in a wrong way so far as i can see, follow the link in my previous comment
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)
I am trying to get response from below REST api. when I open that URL in browser, I gets xml repsonse from server. but when I am trying to get the same using java program I am getting below exception
IOEXCeption
java.net.UnknownHostException: rxnav.nlm.nih.gov
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.plainConnect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.connect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at java.net.HttpURLConnection.getResponseCode(Unknown Source)
at com.test.demo.RestConnector.run(RestConnector.java:22)
at java.lang.Thread.run(Unknown Source)
Pls help me regarding this
below is the code
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 RestConnector implements Runnable{
#Override
public void run() {
String URLString = "http://rxnav.nlm.nih.gov/REST/classes?src=MESH";
try {
URL url = new URL(URLString);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Accept", "application/xml");
if(connection.getResponseCode() != 200){
System.out.println("Failed to connect:"+connection.getResponseCode());
System.out.println("Response Message:"+connection.getResponseMessage());
}
System.out.println("I am here ");
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line ;
while((line = reader.readLine()) != null){
System.out.println(line);
}
connection.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
System.out.println("IOEXCeption");
e.printStackTrace();
}
}
public static void main(String[] args) {
Thread t = new Thread(new RestConnector());
t.start();
}
}
1) The error clearly says "can't resolve hostname".
2) Q: Does your AndroidManifest.xml grant Internet permissions? Make sure it contains this line:
<uses-permission android:name="android.permission.INTERNET" />
3) Q: is this a real device, or an emulator? If the latter, consider recreating your AVD. Believe it or not, that can sometimes help: Android java.net.UnknownHostException: Host is unresolved.
4) Finally, here are some other tips - including proxy server configuration - that might help:
http://eliasbland.wordpress.com/2011/02/22/java-net-unknownhostexception-on-android-a-list-of-possible-causes/
I have a major problem during loading the extension into the program. I get an exception as there is no valid constructor.
The problem is in the line:
ekstensja = (ArrayList<Dydaktyk>) ois.readObject();
I get something like that:
java.io.InvalidClassException: Dydaktyk; no valid constructor
at java.io.ObjectStreamClass$ExceptionInfo.newInvalidClassException(Unknown Source)
at java.io.ObjectStreamClass.checkDeserialize(Unknown Source)
at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source)
at java.util.ArrayList.readObject(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at java.io.ObjectStreamClass.invokeReadObject(Unknown Source)
at java.io.ObjectInputStream.readSerialData(Unknown Source)
at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source)
at Dydaktyk.wczytajEkstensje(Dydaktyk.java:81)
at Dydaktyk.<clinit>(Dydaktyk.java:69)
at java.io.ObjectStreamClass.hasStaticInitializer(Native Method)
at java.io.ObjectStreamClass.computeDefaultSUID(Unknown Source)
at java.io.ObjectStreamClass.access$100(Unknown Source)
at java.io.ObjectStreamClass$1.run(Unknown Source)
at java.io.ObjectStreamClass$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.io.ObjectStreamClass.getSerialVersionUID(Unknown Source)
at java.io.ObjectStreamClass.initNonProxy(Unknown Source)
at java.io.ObjectInputStream.readNonProxyDesc(Unknown Source)
at java.io.ObjectInputStream.readClassDesc(Unknown Source)
at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.defaultReadFields(Unknown Source)
at java.io.ObjectInputStream.readSerialData(Unknown Source)
at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source)
at java.util.ArrayList.readObject(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at java.io.ObjectStreamClass.invokeReadObject(Unknown Source)
at java.io.ObjectInputStream.readSerialData(Unknown Source)
at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.defaultReadFields(Unknown Source)
at java.io.ObjectInputStream.readSerialData(Unknown Source)
at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source)
at java.util.ArrayList.readObject(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at java.io.ObjectStreamClass.invokeReadObject(Unknown Source)
at java.io.ObjectInputStream.readSerialData(Unknown Source)
at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source)
at Przedmiot.wczytajEkstensje(Przedmiot.java:99)
at Przedmiot.<clinit>(Przedmiot.java:87)
at GUI.main(GUI.java:100)
static {
wczytajEkstensje(); // load Extension
}
public static void wczytajEkstensje() {// load extension
FileInputStream fis = null;
ObjectInputStream ois = null;
try {
fis = new FileInputStream("dydaktyk.ser");
ois = new ObjectInputStream(fis);
// here is the problem
ekstensja = (ArrayList<Dydaktyk>) ois.readObject();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
try {
if (ois != null) {
ois.close();
}
} catch (IOException e) {
}
try {
if (fis != null) {
fis.close();
}
} catch (IOException e) {
}
}
}
public static void zapiszEkstensje() {// save extension
FileOutputStream fos = null;
ObjectOutputStream oos = null;
try {
fos = new FileOutputStream("dydaktyk.ser");
oos = new ObjectOutputStream(fos);
oos.writeObject(ekstensja); // serialization
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (oos != null) {
oos.close();
}
} catch (IOException e) {
}
try {
if (fos != null) {
fos.close();
}
} catch (IOException e) {
}
}
}
The class Dydaktyk should have an accessible (public or protected) no-args constructor so that the serialization reflection mechanism can create an instance of the class:
public Dydaktyk() {
...
}
From the docs
During deserialization, the fields of non-serializable classes will be initialized using the public or protected no-arg constructor of the class. A no-arg constructor must be accessible to the subclass that is serializable. The fields of serializable subclasses will be restored from the stream.
As specified in Oracle site about Serialization interface :
During deserialization, the fields of non-serializable classes will be
initialized using the public or protected no-arg constructor of the
class. A no-arg constructor must be accessible to the subclass that is
serializable. The fields of serializable subclasses will be restored
from the stream.
What I gues is that Dydaktyk is the subclass of some class. And you have defined the parametric constructor within the superclass and have not defined a parameter-less constructor within it . And the compiler isn't inserting a default constructor for that superclass. So , You should define a parameter-less constructor within your superclass also.
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;