Skip to content

Commit 752ad18

Browse files
committed
Initial push
1 parent ffc1c4c commit 752ad18

7 files changed

Lines changed: 475 additions & 0 deletions

File tree

HttpExample/input/test.txt

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Hello from Client to Server!
2+
Challenge: This is a second line!

HttpExample/output/test.txt

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Hello from Client to Server!
2+
Challenge: This is a second line!
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
package de.quoss.example.httpexample;
2+
3+
import java.io.FileInputStream;
4+
import java.io.InputStream;
5+
import java.io.OutputStream;
6+
import java.net.HttpURLConnection;
7+
import java.net.URL;
8+
import java.util.logging.Level;
9+
import java.util.logging.Logger;
10+
11+
public class HttpClient2Example {
12+
13+
private static final String CLASS_NAME = HttpClient2Example.class.getName();
14+
15+
private static final Logger LOGGER = Logger.getLogger(CLASS_NAME);
16+
17+
private static final String FILENAME = "test.txt";
18+
19+
private static final String REQUEST_METHOD_POST = "POST";
20+
21+
private HttpClient2Example() throws Exception {
22+
super();
23+
String urlString = String.format("http://localhost:8080/test?filename=%s", FILENAME);
24+
// String urlString = "http://localhost:8080/test";
25+
String charset = "UTF-8";
26+
URL url = new URL(urlString);
27+
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
28+
httpURLConnection.setRequestMethod(REQUEST_METHOD_POST);
29+
httpURLConnection.setDoOutput(true);
30+
httpURLConnection.setRequestProperty("Accept-Charset", charset);
31+
httpURLConnection.setRequestProperty("Content-Type", "text/plain");
32+
InputStream inputStream = new FileInputStream("input\\".concat(FILENAME));
33+
byte[] b = new byte[1024];
34+
int bytesRead;
35+
int overallBytesRead = 0;
36+
StringBuilder stringBuilder = new StringBuilder();
37+
while ((bytesRead = inputStream.read(b)) != -1) {
38+
stringBuilder.append(new String(b).substring(0, bytesRead));
39+
overallBytesRead += bytesRead;
40+
}
41+
inputStream.close();
42+
httpURLConnection.setRequestProperty("Content-Length", Integer.toString(overallBytesRead));
43+
OutputStream outputStream = httpURLConnection.getOutputStream();
44+
outputStream.write(stringBuilder.toString().getBytes());
45+
outputStream.close();
46+
int responseCode = httpURLConnection.getResponseCode();
47+
LOGGER.log(Level.INFO, "[responseCode={0}]", new Object[] { responseCode });
48+
inputStream = httpURLConnection.getInputStream();
49+
int contentLength = httpURLConnection.getContentLength();
50+
bytesRead = inputStream.read(b);
51+
while ((bytesRead = inputStream.read(b)) != -1) {
52+
LOGGER.log(Level.INFO, new String(b).substring(0, bytesRead));
53+
}
54+
inputStream.close();
55+
httpURLConnection.disconnect();
56+
}
57+
58+
public static void main(String[] args) throws Exception {
59+
new HttpClient2Example();
60+
}
61+
62+
}
Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
package de.quoss.example.httpexample;
2+
3+
import java.io.IOException;
4+
import java.net.HttpURLConnection;
5+
import java.net.ProtocolException;
6+
import java.net.URL;
7+
import java.util.logging.Level;
8+
import java.util.logging.Logger;
9+
10+
/**
11+
*
12+
* <p>
13+
* example how to send a http request and receive the response
14+
* </p>
15+
*
16+
* <p>
17+
* TODO use properties to customize client behaviour
18+
* </p>
19+
* <p>
20+
* TODO integrate client 2 example
21+
* </p>
22+
*
23+
* @author Clemens Quoss
24+
*
25+
*/
26+
class HttpClientExample {
27+
28+
/**
29+
* classname
30+
*/
31+
private static final String CLASS_NAME = HttpClientExample.class.getName();
32+
33+
/**
34+
* logger
35+
*/
36+
private static final Logger LOGGER = Logger.getLogger(CLASS_NAME);
37+
38+
/**
39+
* private working constructor
40+
*/
41+
private HttpClientExample() throws HttpExampleException {
42+
43+
// start message
44+
LOGGER.log(Level.INFO, "start");
45+
46+
// try to open http connection
47+
HttpURLConnection httpURLConnection = null;
48+
try {
49+
httpURLConnection = (HttpURLConnection) new URL("http://localhost:8080/?param1=value1&param2=value2")
50+
.openConnection();
51+
} catch (IOException e) {
52+
throw new HttpExampleException(e);
53+
}
54+
55+
// try to set GET request method
56+
try {
57+
httpURLConnection.setRequestMethod("GET");
58+
} catch (ProtocolException e) {
59+
throw new HttpExampleException(e);
60+
}
61+
62+
// try to connect
63+
try {
64+
httpURLConnection.connect();
65+
} catch (IOException e) {
66+
throw new HttpExampleException(e);
67+
}
68+
69+
// try to log response code
70+
try {
71+
int responseCode = httpURLConnection.getResponseCode();
72+
LOGGER.log(Level.INFO, "Response code: {0}", new Object[] { responseCode });
73+
} catch (IOException e) {
74+
throw new HttpExampleException(e);
75+
}
76+
77+
// try to log response message
78+
try {
79+
String responseMessage = httpURLConnection.getResponseMessage();
80+
LOGGER.log(Level.INFO, "Response message: {0}", new Object[] { responseMessage });
81+
} catch (IOException e) {
82+
throw new HttpExampleException(e);
83+
}
84+
85+
// end message
86+
LOGGER.log(Level.INFO, "end");
87+
88+
}
89+
90+
public static void main(String[] args) {
91+
92+
// try to call private working constructor
93+
try {
94+
new HttpClientExample();
95+
} catch (HttpExampleException e) {
96+
LOGGER.log(Level.SEVERE, "", e);
97+
System.exit(1);
98+
}
99+
100+
}
101+
102+
}
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
package de.quoss.example.httpexample;
2+
3+
/**
4+
* exception for handling errors
5+
*
6+
* @author Clemens Quoß
7+
*
8+
*/
9+
class HttpExampleException extends Exception {
10+
11+
/**
12+
* default serial version id
13+
*/
14+
private static final long serialVersionUID = 1L;
15+
16+
/**
17+
* constructor with message
18+
*
19+
* @param msg
20+
* message
21+
*/
22+
HttpExampleException(String msg) {
23+
24+
// call super
25+
super(msg);
26+
27+
}
28+
29+
/**
30+
* constructor with exception
31+
*
32+
* @param e
33+
* exception
34+
*/
35+
HttpExampleException(Exception e) {
36+
37+
// call super
38+
super(e);
39+
40+
}
41+
42+
}
Lines changed: 105 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,105 @@
1+
package de.quoss.example.httpexample;
2+
3+
import java.io.FileWriter;
4+
import java.io.IOException;
5+
import java.io.InputStream;
6+
import java.io.OutputStream;
7+
import java.net.InetSocketAddress;
8+
import java.util.HashMap;
9+
import java.util.Map;
10+
import java.util.logging.Level;
11+
import java.util.logging.Logger;
12+
13+
import com.sun.net.httpserver.Headers;
14+
import com.sun.net.httpserver.HttpExchange;
15+
import com.sun.net.httpserver.HttpHandler;
16+
import com.sun.net.httpserver.HttpServer;
17+
18+
class HttpServer2Example {
19+
20+
private static final String CLASS_NAME = HttpServer2Example.class.getName();
21+
22+
private static final Logger LOGGER = Logger.getLogger(CLASS_NAME);
23+
24+
private static final String REQUEST_METHOD_GET = "GET";
25+
26+
private static final String REQUEST_METHOD_POST = "POST";
27+
28+
private HttpServer2Example() throws Exception {
29+
super();
30+
HttpServer httpServer = HttpServer.create(new InetSocketAddress(8080), 0);
31+
httpServer.createContext("/test", new HttpHandlerExample());
32+
httpServer.start();
33+
}
34+
35+
private class HttpHandlerExample implements HttpHandler {
36+
37+
@Override
38+
public void handle(HttpExchange httpExchange) throws IOException {
39+
String requestMethod = httpExchange.getRequestMethod();
40+
LOGGER.log(Level.INFO, " [requestMethod={0}]", new Object[] { requestMethod });
41+
Headers headers = httpExchange.getRequestHeaders();
42+
LOGGER.log(Level.INFO, " [headers.entrySet()={0}]", new Object[] { headers.entrySet() });
43+
String response;
44+
int responseCode;
45+
if (REQUEST_METHOD_GET.equals(requestMethod)) {
46+
Map<String, String> query = queryToMap(httpExchange.getRequestURI().getQuery());
47+
LOGGER.log(Level.INFO, " [query={0}]", new Object[] { query });
48+
response = "This is the response";
49+
responseCode = 200;
50+
httpExchange.sendResponseHeaders(200, response.length());
51+
OutputStream outputStream = httpExchange.getResponseBody();
52+
outputStream.write(response.getBytes());
53+
outputStream.close();
54+
} else if (REQUEST_METHOD_POST.equals(requestMethod)) {
55+
Map<String, String> query = queryToMap(httpExchange.getRequestURI().getQuery());
56+
LOGGER.log(Level.INFO, " [query={0}]", new Object[] { query });
57+
String filename = query.get("filename");
58+
InputStream inputStream = httpExchange.getRequestBody();
59+
int bytesRead;
60+
byte[] b = new byte[1024];
61+
StringBuilder stringBuilder = new StringBuilder();
62+
while ((bytesRead = inputStream.read(b)) != -1) {
63+
stringBuilder.append(new String(b).substring(0, bytesRead));
64+
}
65+
LOGGER.log(Level.INFO, " [stringBuilder={0}]", new Object[] { stringBuilder.toString() });
66+
if (filename != null) {
67+
FileWriter fileWriter = new FileWriter("output\\".concat(filename));
68+
fileWriter.write(stringBuilder.toString());
69+
fileWriter.close();
70+
response = String.format("File received: %s", filename);
71+
} else {
72+
response = "No file received.";
73+
}
74+
responseCode = 200;
75+
} else {
76+
LOGGER.log(Level.INFO, "not supported [requestMethod={0}]", new Object[] { requestMethod });
77+
response = String.format("Request method not supported: %s", requestMethod);
78+
responseCode = 501;
79+
}
80+
httpExchange.sendResponseHeaders(responseCode, response.length());
81+
OutputStream outputStream = httpExchange.getResponseBody();
82+
outputStream.write(response.getBytes());
83+
outputStream.close();
84+
}
85+
86+
private Map<String, String> queryToMap(String query) {
87+
Map<String, String> result = new HashMap<String, String>();
88+
for (String param : query.split("&")) {
89+
String[] pair = param.split("=");
90+
if (pair.length > 1) {
91+
result.put(pair[0], pair[1]);
92+
} else {
93+
result.put(pair[0], "");
94+
}
95+
}
96+
return result;
97+
}
98+
99+
}
100+
101+
public static void main(String[] args) throws Exception {
102+
new HttpServer2Example();
103+
}
104+
105+
}

0 commit comments

Comments
 (0)