I'm using com.sun.net.HttpServer class to build a http server with java like the following:
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.concurrent.Executors;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
public class SimpleHttpServer {
public static void main(String[] args) throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress(8989), 0);
server.createContext("/", new MyHandler());
server.setExecutor(null); // creates a default executor
server.start();
}
static class MyHandler implements HttpHandler {
public void handle(HttpExchange t) throws IOException {
//Read the request
InputStream in = httpExchange.getRequestBody();
StringWriter writer = new StringWriter();
IOUtils.copy(in, writer);
String inputString = writer.toString();
//prepare the response
httpExchange.sendResponseHeaders(200, "Hi my faithful client".length());
OutputStream os = httpExchange.getResponseBody();
os.write("Hi my faithful client".getBytes());
os.close();
}
}
}
I'm communicating with this server using this client:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
public class Main {
public static void main(String argv[]) throws IOException{
String urlstr = "http://127.0.0.1:8989";
URL url = new URL(urlstr);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
writer.write("Hello HTTP server!! I'm your client1");
InputStream in = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder result = new StringBuilder();
String line;
while((line = reader.readLine()) != null) {
result.append(line);
System.out.println(result.toString());
}
}
}
and it'fine working.
but what I want now is that the server allows the client to communicate with him for a session that means a sequence of request/response not just only one. So it will be a loop of request/response. For this purpose I tried to add as a first step just one request to the client by adding to it those two lines:
writer.flush();
writer.write("Hello HTTP server!! I'm your client2");
But it doesn't work. Just the first request is caught by the server.
How can I change the code to achieve my purpose?
Please check the code below:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
public class Test1 {
static String urlstr = "http://127.0.0.1:8989";
public static void main(String argv) throws IOException{
URL url = new URL(urlstr);
Test1 t = new Test1();
for (int i = 0; i < 10; i++) {
t.sendRequest("Hello HTTP server!! I'm your client" + i, url);
}
}
private void sendRequest(String strToSend, URL url) throws IOException{
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
writer.write(strToSend);
InputStream in = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder result = new StringBuilder();
String line;
while((line = reader.readLine()) != null) {
result.append(line);
System.out.println(result.toString());
}
}
}
Related
I want to print the values in the url but I'm new can you help me?
......................................................
import java.util.*;
import java.io.*;
import java.net.*;
class Main {
public static void main (String[] args) {
System.setProperty("http.agent", "Chrome");
try {
URL url = new URL("https://coderbyte.com/api/challenges/json/rest-get-simple");
try {
URLConnection connection = url.openConnection();
InputStream inputStream = connection.getInputStream();
System.out.println(inputStream);
} catch (IOException ioEx) {
System.out.println(ioEx);
}
} catch (MalformedURLException malEx) {
System.out.println(malEx);
}
}
}
try this
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
public class UrlConnectionReader {
public static void main(String[] args) throws MalformedURLException, IOException {
InputStream in = null;
System.setProperty("http.agent", "Chrome");
try {
in = new URL("https://coderbyte.com/api/challenges/json/rest-get-simple").openStream();
InputStreamReader inR = new InputStreamReader(in);
BufferedReader buf = new BufferedReader(inR);
String line;
while ((line = buf.readLine()) != null) {
System.out.println(line);
}
} finally {
in.close();
}
}
}
Background: I'm getting introduced to clients and servers, and decided to make a simple proxy server.
What the code does as of now: The client side asks for a www.(enter site here).whatever (org, com, edu, etc.) then, the server takes that input in, and calls my WebsiteToHTML class, which converts that whole page to a byte array. The server then stores that byte array to it's own byte array variable. The server then sends the size of that array back to the client, and then sends the byte array itself back to the client. Then, the client makes a byte array of the size sent from the server, and then makes the byte array equal to the byte array that the server sent back. I then have an html string that is made from looping through the byte array and appending all of the chars to the String. I then use WebView to output that String using the loadContent function.
My Problem: My problem lies in outputting images. For instance, if I wanted to go to www.google.com, my code would run perfectly, and the WebView does indeed output the google page. However, the big "Google" logo simply just says "google" in text. My guess is that the WebView doesn't pull the images from the href in the html. Thus, I am here.
My Code:
ProxyClient:
package proxy;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
import java.awt.AWTEvent;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.URL;
import javax.swing.JButton;
import javafx.application.*;
import javafx.scene.Scene;
import javafx.scene.layout.VBox;
import javafx.scene.web.WebView;
import javafx.stage.Stage;
#SuppressWarnings("restriction")
public class ProxyClient extends Application{
public static void main(String[] args) throws UnknownHostException, IOException, InterruptedException {
launch(args);
}
#Override
public void start(Stage primaryStage) throws Exception {
final String IP = "localhost";
byte[] b;
final int PORT = 4444;
String input;
Socket s = new Socket(IP,PORT);
DataOutputStream out = new DataOutputStream(s.getOutputStream());
Scanner scan = new Scanner(System.in);
InputStream inFromServer = s.getInputStream();
DataInputStream in = new DataInputStream(inFromServer);
String html = "";
System.out.println("Enter URL: ");
input = scan.next();
out.writeUTF(input);
System.out.println("output sent: " + input);
byte[] htmlBytes = new byte[in.readInt()];
in.read(htmlBytes);
for(int i = 0; i < htmlBytes.length; i++) {
char c = (char)(htmlBytes[i] >= 0 ? htmlBytes[i] : htmlBytes[i]+256);
html += c;
}
System.out.println(html);
primaryStage.setTitle("Proxy Client");
WebView webView = new WebView();
webView.getEngine().loadContent(html);
VBox vBox = new VBox(webView);
Scene scene = new Scene(vBox, 960, 600);
primaryStage.setScene(scene);
primaryStage.show();
}
}
Proxy Server:
package proxy;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Arrays;
public class ProxyServer {
public static void main(String[] args) throws IOException, InterruptedException {
final int PORT = 4444;
ServerSocket ss = new ServerSocket(PORT);
Socket s = ss.accept();
System.out.println("Connection Established");
DataInputStream in = new DataInputStream(s.getInputStream());
DataOutputStream out = new DataOutputStream(s.getOutputStream());
WebsiteToHTML converter;
String site;
site = "https://"+in.readUTF();
converter = new WebsiteToHTML(site);
byte[] html = converter.write();
System.out.println("Link Receieved received: " + site);
System.out.println("Converted HTMLto byte array: " + Arrays.toString(html));
while(true) {
out.writeInt(html.length);
out.write(html);
}
}
}
WebsiteToHTML:
package proxy;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import javax.net.ssl.HttpsURLConnection;
public class WebsiteToHTML {
URL myurl;
String html;
HttpsURLConnection con;
InputStream ins;
InputStreamReader isr;
BufferedReader in;
String masterString = "";
byte[] b;
public WebsiteToHTML(String httpsURL) throws IOException {
myurl = new URL(httpsURL);
con = (HttpsURLConnection) myurl.openConnection();
ins = con.getInputStream();
isr = new InputStreamReader(ins);
in = new BufferedReader(isr);
}
public byte[] write() throws IOException {
String inputLine;
while ((inputLine = in.readLine()) != null) {
masterString += inputLine + "\n";
}
b = masterString.getBytes();
b = masterString.getBytes(Charset.forName("UTF-8"));
in.close();
return b;
}
}
I'm having an error while using the apache PDFBox jar. It seems like somehow it is calling a method on the AFMParser class which is non-existent. AFAIK I have included fontbox properly. pdfbox,fontbox,commons and gson are all in my build path.
I guess the error must have something to do with referencing, but this is my first JAVA project and no real clue how to debug this further. If anyone has an idea, please advice.
Error log:
2018-03-16 14:26:50.020 java[1898:217675] java.lang.NoSuchMethodError: org.apache.fontbox.afm.AFMParser.parse()V
at org.apache.pdfbox.pdmodel.font.PDFont.addAdobeFontMetric(PDFont.java:166)
at org.apache.pdfbox.pdmodel.font.PDFont.addAdobeFontMetric(PDFont.java:152)
at org.apache.pdfbox.pdmodel.font.PDFont.getAdobeFontMetrics(PDFont.java:122)
at org.apache.pdfbox.pdmodel.font.PDFont.<clinit>(PDFont.java:114)
at org.apache.pdfbox.pdmodel.font.PDFontFactory.createFont(PDFontFactory.java:108)
at org.apache.pdfbox.pdmodel.PDResources.getFonts(PDResources.java:213)
at org.apache.pdfbox.util.PDFStreamEngine.getFonts(PDFStreamEngine.java:612)
at org.apache.pdfbox.util.operator.SetTextFont.process(SetTextFont.java:69)
at org.apache.pdfbox.util.PDFStreamEngine.processOperator(PDFStreamEngine.java:562)
at org.apache.pdfbox.util.PDFStreamEngine.processSubStream(PDFStreamEngine.java:269)
at org.apache.pdfbox.util.PDFStreamEngine.processSubStream(PDFStreamEngine.java:236)
at org.apache.pdfbox.util.PDFStreamEngine.processStream(PDFStreamEngine.java:216)
at org.apache.pdfbox.pdfviewer.PageDrawer.drawPage(PageDrawer.java:139)
at org.apache.pdfbox.pdmodel.PDPage.print(PDPage.java:890)
at java.desktop/sun.lwawt.macosx.CPrinterJob$6.run(CPrinterJob.java:757)
at java.desktop/sun.lwawt.macosx.CPrinterJob.printAndGetPageFormatArea(CPrinterJob.java:767)
at java.desktop/sun.lwawt.macosx.CPrinterJob.printLoop(Native Method)
at java.desktop/sun.lwawt.macosx.CPrinterJob.print(CPrinterJob.java:334)
at java.desktop/sun.print.RasterPrinterJob.print(RasterPrinterJob.java:1443)
at org.apache.pdfbox.pdmodel.PDDocument.print(PDDocument.java:1545)
at org.apache.pdfbox.pdmodel.PDDocument.silentPrint(PDDocument.java:1531)
at com.xlshopgroup.printingpc.WatchFolder.printPDFFromURL(WatchFolder.java:83)
at com.xlshopgroup.printingpc.WatchFolder.main(WatchFolder.java:118)
Exception: Error: End-of-File, expected line
My code:
import java.nio.file.*;
import java.io.*;
import java.net.*;
import java.nio.channels.FileChannel;
import java.nio.ByteBuffer;
import java.awt.print.PrinterJob;
import java.awt.print.PageFormat;
import java.awt.print.Book;
import java.awt.print.*;
import java.awt.print.PrinterJob;
import javax.print.PrintService;
import javax.net.ssl.HttpsURLConnection;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.*;
import org.apache.pdfbox.PrintPDF;
import org.apache.commons.*;
import org.apache.fontbox.*;
import com.google.gson.*;
public class WatchFolder {
public static JsonObject sendPost(
String APIURL
) throws Exception {
String APIBASEURL = "http://example.com";
URL obj = new URL(APIBASEURL+APIURL);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
//HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.flush();
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
JsonObject convertedObject = new Gson().fromJson(response.toString(), JsonObject.class);
return convertedObject;
}
public static void printPDFFromURL(
String pdfURL,
String printerName
) throws IOException,PrinterException {
PDDocument document = null;
try {
document = PDDocument.load(new URL(pdfURL));
PrinterJob printJob = PrinterJob.getPrinterJob();
printJob.setJobName(pdfURL);
if(printerName != null ) {
PrintService[] printService = PrinterJob.lookupPrintServices();
boolean printerFound = false;
for(int i = 0;!printerFound && i < printService.length; i++) {
if(printService[i].getName().indexOf(printerName) != -1) {
printJob.setPrintService(printService[i]);
printerFound = true;
System.out.println("Printer found: " + printService[i].getName());
}
}
}
document.silentPrint( printJob );
}catch(Exception e) {
System.out.println("Exception: "+e.getMessage());
}finally {
if(document != null) {
document.close();
}
}
}
public static void main(
String[] args
) throws Exception {
JsonObject toBePrinted = sendPost("gettoprint");
JsonObject response = toBePrinted.getAsJsonObject("response");
JsonArray results = response.getAsJsonArray("results");
for (JsonElement result : results) {
JsonObject resultObj = result.getAsJsonObject();
String PackingSlipURL = resultObj.get("packing_slip_url").getAsString();
String StickerURL = resultObj.get("sticker_url").getAsString();
String ShippingPartner = resultObj.get("shipping_partner").getAsString();
String id = resultObj.get("id").getAsString();
printPDFFromURL(PackingSlipURL, "HP-idealbetalingen-printer");
printPDFFromURL(StickerURL, "Zebra?");
//JsonObject deletedFromQueue = sendPost("deletefromqueue/"+id);
}
}
}
#self; indeed as John Kane suggested, it had to do with version numbering. I was trying to use a 2.x.x version of fontbox with a 1.8.x version of pdfbox.
My server looks like this:
package marshexample;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.net.ServerSocket;
import java.net.Socket;
public class marshServer {
private ServerSocket ses;
private Reader br;
private OutputStream os;
public marshServer() {
StringBuilder sb = new StringBuilder();
try {
ses = new ServerSocket(7824);
Socket s = ses.accept();
br = new InputStreamReader(s.getInputStream());
char[] request = new char[6];
int count = br.read(request);
while (!sb.toString().contains("project")) {
sb.append(new String(request, 0, count));
count = br.read(request);
System.out.println(sb.toString());
}
System.out.println(sb);
os = s.getOutputStream();
os.write("string from server".getBytes());
os.write("empty line".getBytes());
os.flush();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(sb);
}}
The issue is I have to add the string os.write("empty line".getBytes()); in order to make it work correctly. Without this string the massage is not fully sent to the client. (The same situation is with client). So why flush method does not solve this problem? Thank you for any ideas!
I am trying to serialize an object in a HttpHandler class.
I have 2 files, Server3.java:
package server3;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.net.InetSocketAddress;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
public class Server3 {
public static void main(String[] args) throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress(3333), 0);
server.createContext("/", new MyHandler());
server.setExecutor(null); // creates a default executor
server.start();
}
static class MyHandler implements HttpHandler {
public void handle(HttpExchange t) throws IOException {
String response = "Kjo eshte nje pergjigje nga serveri! n";
t.sendResponseHeaders(200, response.length());
OutputStream os = t.getResponseBody();
os.write(response.getBytes());
os.close();
Personat obj = new Personat();
ObjectOutputStream objOut = new ObjectOutputStream(t.getResponseBody());
objOut.writeObject(obj);
objOut.close();
}
}
}
class Personat implements Serializable{
private static final long serialVersionUID = 1L;
int ID=3;
String Name="Andi";
}
and Client3.java:
package server3;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.net.HttpURLConnection;
import java.net.URL;
//te gjithe personat qe jan ne database me nej objekt
public class Client3 {
public static void main(String[] args) throws Exception {
try {
URL url = new URL("http://localhost:3333");
HttpURLConnection s = (HttpURLConnection) url.openConnection();
s.setDoOutput(true);
s.setDoInput(true);
s.setRequestMethod("POST");
s.setUseCaches(false);
InputStream in = s.getInputStream();
InputStreamReader isr = new InputStreamReader(in);
BufferedReader br = new BufferedReader(isr);
int c;
while ((c = br.read()) != -1) {
System.out.print((char) c);
}
ObjectInputStream ios = new ObjectInputStream(s.getInputStream());
Personat oin = (Personat) ios.readObject();
String emri=oin.Name;
System.out.println(emri);
ios.close();
s.disconnect();
} catch (IOException ex) {
System.err.println(ex);
System.out.print(ex);
}
}
}
But when I run it eclipse shows me
java.io.EOFException Kjo eshte nje pergjigje nga serveri! njava.io.EOFException`
and I cant understand why.
The problem is that you are trying to fit both the string response and the object into response.length() bytes. What happens is that only response.length() bytes are sent and so if you try to read more you get the EOFException.
If you instead set the responseLength parameter to be 0 it will allow you to transmit an arbitrary amount of data
t.sendResponseHeaders(200, 0);
You also shouldn't close the stream if you are going to write more data into it. Don't call os.close() until all the writing is complete.