below code is for getting html web page
import java.net.*;
import java.io.*;
import java.io.File; // Import the File class
import java.io.IOException; // Import the IOException class to handle errors
public class TestClass2 {
public static void main(String[] args) throws Exception {
try{
URL url = new URL("https://stackoverflow.com/");
HttpURLConnection urlConnection=(HttpURLConnection)url.openConnection();
BufferedReader reader = new BufferedReader( new InputStreamReader(url.openStream()));
String line;
while ((line = reader.readLine()) != null)
{
System.out.println(line+"\n");
}
reader.close();
}catch(Exception ex){
System.out.println(ex);
}
}
}
but when compile and run that below error occur:
javax.net.ssl.SSLException: Received fatal alert: protocol_version.
how can fix it?
thanks.
This could be that the SSL Certificate is out of date? Have you tried using HttpsURLConnection? Try this first
Revised Code
import java.net.*;
import java.io.*;
import java.io.File; // Import the File class
import java.io.IOException; // Import the IOException class to handle errors
public class TestClass2 {
public static void main(String[] args) throws Exception {
try{
URL url = new URL("https://stackoverflow.com/");
HttpsURLConnection urlConnection=(HttpsURLConnection)url.openConnection();
BufferedReader reader = new BufferedReader( new InputStreamReader(url.openStream()));
String line;
while ((line = reader.readLine()) != null)
{
System.out.println(line+"\n");
}
reader.close();
}catch(Exception ex){
System.out.println(ex);
}
}
}
Related
I have been working with java to make it where i check if a certain user if live and it will say true or false if the user is streaming...im working with minimal json.
here is my code
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import com.eclipsesource.json.JsonObject;
public class hostbot {
public static void main(String[] args) throws Exception {
Twitchbot bot = new Twitchbot();
bot.setVerbose(true);
bot.connect("irc.twitch.tv", 6667, "something");
}
public boolean isStreamLive()
{
try
{
URL url = new URL("https://api.twitch.tv/kraken/streams/rexephon");
URLConnection conn = url.openConnection();
BufferedReader br = new BufferedReader( new InputStreamReader( conn.getInputStream() ));
String inputLine = br.readLine();
br.close();
JsonObject jsonObj = JsonObject.readFrom(inputLine);
return ( jsonObj.get("stream").isNull() )?false:true;
}
catch (IOException e)
{
e.printStackTrace();
}
return false;
}
}
when i return false is that suppose to print in the log the word false? or something else?
package prgms;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
class new_experi
{
public static void main(String[] args) throws IOException
{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter out = new BufferedWriter(new FileWriter("C://Users//Abhilasha U//Desktop//output.txt"));
try
{
Process p=Runtime.getRuntime().exec("cmd /c dir");
p.waitFor();
BufferedReader reader=new BufferedReader(
new InputStreamReader(p.getInputStream())
);
String line;
while((line = reader.readLine()) != null)
{
System.out.println(line);
}
}
catch(IOException e1) {}
System.out.println("Done");
}
}
Answer is simple.
package prgms;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
class new_experi
{
public static void main(String[] args) throws IOException
{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter out = new BufferedWriter(new FileWriter("C://Users//Abhilasha U//Desktop//output.txt"));
try
{
Process p=Runtime.getRuntime().exec("cmd /c dir");
p.waitFor();
BufferedReader reader=new BufferedReader(
new InputStreamReader(p.getInputStream())
);
String line;
while((line = reader.readLine()) != null)
{
System.out.println(line);
}
}
catch(IOException e1) {}
System.out.println("Done");
// This will pause your application so that you can take a screen shot !!
System.in.read();
}
}
If you are running this on an IDE, compile this program and run it. Once it is seen in the console. Press Alt + Print screen button then it will print screen your console.
When I type this following URL into my browser, Bugzilla answers with XML:
http://bugzilla.mycompany.local/buglist.cgi?ctype=rdf&bug_status=CONFIRMED&product=MyProduct
I want to process this XML in a Java program. But when I use the exact same URL in my Java program, Bugzilla answers with HTML instead of XML.
This is my program:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
public class Test {
public static void main(String[] args)
throws IOException {
URL url = new URL("http://bugzilla.mycompany.local/buglist.cgi?ctype=rdf&bug_status=CONFIRMED&product=MyProduct");
URLConnection connection = url.openConnection();
final StringBuilder response = new StringBuilder(1024);
try(InputStreamReader isr = new InputStreamReader(connection.getInputStream())) {
try(BufferedReader reader = new BufferedReader(isr)) {
String inputLine = null;
while((inputLine = reader.readLine()) != null) {
response.append(inputLine);
response.append('\n');
}
}
}
System.out.println(response);
}
}
What am I doing wrong?
The resulting HTML is not the result of the query. It's Bugzillas log-in form. Duh!
I am developing code to send multiple file names to server side and then making sure server recieves those contents and writes it to a file in its own folder. Its working well when I type first file name but when I type second file name the code kind of gets stuck.
Here is my client code:-
package fileTransfer;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class EchoClient {
public static void main(String[] args) throws UnknownHostException {
try {
Socket clientSock=new Socket("localhost",8888);
//to read from server
BufferedReader br=new BufferedReader(new InputStreamReader(clientSock.getInputStream())); //to read
//to write to server
PrintWriter pw=new PrintWriter(clientSock.getOutputStream(), true);
//for user input
BufferedReader userIn=new BufferedReader(new InputStreamReader(System.in));
BufferedReader fileContent=null;
String str=null;
String fileContentLine=null;
while(true){
if((str=br.readLine()).contains("file name")) //recieve echo from server
System.out.println(str);
str=userIn.readLine(); //read user input
fileContent=new BufferedReader(new FileReader(str));
pw.println(str);
while((fileContentLine=fileContent.readLine()) != null){
pw.println(fileContentLine);
}
while((str=br.readLine())!=null)
System.out.println(str);
pw.flush();
}
}catch(IOException e){
e.printStackTrace();
}
}
}
And here is my server code
package fileTransfer;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class EchoServer {
public static void main(String[] args){
try {
ServerSocket serverSock=new ServerSocket(8888);
System.out.println("Waiting for client");
Socket connectFromClient=serverSock.accept();
File file=null;
//reading data from client
BufferedReader input=new BufferedReader(new InputStreamReader(connectFromClient.getInputStream()));
//will write back to client
PrintWriter pr=new PrintWriter(new OutputStreamWriter(connectFromClient.getOutputStream()));
PrintWriter writeToFile=null;
//sending following statements to client
pr.println("Connection established with server! Give a file name");
pr.flush();
String response;
while(true){
while((response=input.readLine()) != null)
{
if(response==null)
break;
else{
System.out.println(response);
if(response.contains(".txt")){
//file=new File("FromClient.txt");
file=new File("FromClient"+response);
if(!file.exists())
file.createNewFile();
writeToFile=new PrintWriter(file);
}
else{
//writeToFile=new PrintWriter(file);
writeToFile.println(response);
}
pr.println("Echo from server -> " + response);
//System.out.println("Adding these contents to a file");
writeToFile.flush();
pr.flush();
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
It´s getting stuck in the client in this lines:
while ((str = br.readLine()) != null) {
System.out.println(str);
}
Waiting for more server lines.
You have to tell the client when to stop from reading file data from socket stream and jump for the next file. For instance you can send before the content of the file the number of bytes you are going to transfer, you read that number of bytes from the stream and then go for the next file.
I post this modifications of your code as an example, as the idea I want to express.
First I get the total linenumber of the file (I suppose text file), and I send it to server, which knows exactly how many lines to read before jumping to next file.
It can be changed to use the total size of the file in bytes, for instance.
This code is no 100% correct, it works, take it as an example.
Client:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class EchoClient {
public static void main(final String[] args) throws UnknownHostException {
try {
final Socket clientSock = new Socket("localhost", 8888);
// to read from server
final BufferedReader br = new BufferedReader(new InputStreamReader(clientSock.getInputStream())); // to
// read
// to write to server
final PrintWriter pw = new PrintWriter(clientSock.getOutputStream(), true);
// for user input
final BufferedReader userIn = new BufferedReader(new InputStreamReader(System.in));
BufferedReader fileContent = null;
String str = null;
String fileContentLine = null;
while (true) {
System.out.println("Print filename");
str = userIn.readLine(); // read user input
fileContent = new BufferedReader(new FileReader(str));
pw.println(str);
// first count the line number:
int lineno = 0;
while ((fileContentLine = fileContent.readLine()) != null) {
lineno++;
}
fileContent.close();
//
fileContent = new BufferedReader(new FileReader(str));
pw.println(String.valueOf(lineno));
while ((fileContentLine = fileContent.readLine()) != null) {
pw.println(fileContentLine);
}
for (int i = 0; i < lineno; i++) {
str = br.readLine();
System.out.println(str);
}
pw.flush();
}
} catch (final IOException e) {
e.printStackTrace();
}
}
}
Server:
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class EchoServer {
public static void main(final String[] args) {
try {
final ServerSocket serverSock = new ServerSocket(8888);
System.out.println("Waiting for client");
final Socket connectFromClient = serverSock.accept();
File file = null;
// reading data from client
final BufferedReader input = new BufferedReader(new InputStreamReader(connectFromClient.getInputStream()));
// will write back to client
final PrintWriter pr = new PrintWriter(new OutputStreamWriter(connectFromClient.getOutputStream()));
PrintWriter writeToFile = null;
// sending following statements to client
pr.println("Connection established with server! Give a file name");
pr.flush();
String response;
while (true) {
final String fileName = input.readLine();
file = new File("FromClient" + fileName);
if (!file.exists()) {
file.createNewFile();
}
writeToFile = new PrintWriter(file);
final String sLineNo = input.readLine();
final int lineno = Integer.parseInt(sLineNo);
for (int i = 0; i < lineno; i++) {
response = input.readLine();
System.out.println(response);
// writeToFile=new PrintWriter(file);
writeToFile.println(response);
pr.println("Echo from server -> " + response);
// System.out.println("Adding these contents to a file");
writeToFile.flush();
pr.flush();
}
writeToFile.close();
}
} catch (final IOException e) {
e.printStackTrace();
}
}
}
I Hope to be helpful.
I am currently having difficulty understanding why my code is not working. I've included my client and server code below. I've figured out that my problem happens somewhere in the while loops but I'm not sure how to fix it so that it doesn't get stuck. I've searched around the forum for a while and some said adding a newline character would fix it, but I'm still having trouble.
My main question is how can I avoid the process from getting stuck and not communicating properly. Can anybody out there point me in the right direction?
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;
public class My_Client {
public static void main(String[] args) throws UnknownHostException, IOException {
Socket s = new Socket("localhost", 5555);
BufferedReader r = new BufferedReader(new InputStreamReader(
s.getInputStream()));
PrintStream w = new PrintStream(s.getOutputStream());
w.print("hello world");
w.print('\n');
String line;
while ((line = r.readLine()) != null) {
System.out.println("Received: " + line);
//System.out.println("Error");
}
w.close();
}
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
-----------------------------------------------------------------
public class My_Server {
private static final int PORT = 5555;
public static void main(String[] args) {
try {
ServerSocket ss = new ServerSocket(PORT);
System.out.println("Server Socket Created");
while (true) {
System.out.println("Waiting on connection");
Socket cs = ss.accept();
System.out.println("Client connected");
BufferedReader r = new BufferedReader(new InputStreamReader(
cs.getInputStream()));
PrintStream w = new PrintStream(cs.getOutputStream());
String line;
while ((line = r.readLine()) != null) {
w.print(line + "!!!!");
w.print('\n');
}
System.out.println("Client disconnected");
r.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Both ends are reading until EOS and neither is closing until after that. So you have a classic deadlock. You need to rethink your application protocol.
You also need to tell your PrintStream or PrintWriter to autoflush, or else call flush() yourself, but this is a relatively minor matter compared to the mistake above.
You should use autoflush on your PrintWriters like this:
PrintStream w = new PrintStream(cs.getOutputStream(),true);
You can setup a PROTOCOL to end the communication something like this:
In your client:
w.println("[END]");
In your server:
while (!(line = r.readLine()).equals("[END]")) {
Hope this helps:
Check the comments
And be sure that you get Client Connected on console of server side
CLIENT SIDE
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;
public class My_Client {
public static void main(String[] args) throws UnknownHostException, IOException {
Socket s = new Socket("localhost", 5555);
BufferedReader r = new BufferedReader(new InputStreamReader(
s.getInputStream()));
PrintStream w = new PrintStream(s.getOutputStream());
w.print("hello world");
w.print("\n"); // enter new line
w.flush();// flush the outputstream
String line;
while ((line = r.readLine()) != null) {
System.out.println("Received: " + line);
//System.out.println("Error");
}
w.close();
}
}
SERVER SIDE
----------------------------------------------------------
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
public class My_Server {
private static final int PORT = 5555;
public static void main(String[] args) {
try {
ServerSocket ss = new ServerSocket(PORT);
System.out.println("Server Socket Created");
while (true) {
System.out.println("Waiting on connection");
Socket cs = ss.accept();
System.out.println("Client connected");
BufferedReader r = new BufferedReader(new InputStreamReader(
cs.getInputStream()));
PrintStream w = new PrintStream(cs.getOutputStream());
String line;
while ((line = r.readLine()) != null) {
w.print(line + "!!!!");
w.print("\n");// entering new line
}
System.out.println("Client disconnected");
r.close();
w.close();// close w
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}