This commit is contained in:
Jonathan Cook
2019-10-23 15:01:44 +02:00
parent db85c8f275
commit 684ec0d2e3
20486 changed files with 1642483 additions and 0 deletions
@@ -0,0 +1,12 @@
## Core Java Networking (Part 2)
This module contains articles about networking in Java
### Relevant Articles
- [Checking if a URL Exists in Java](https://www.baeldung.com/java-check-url-exists)
- [Making a JSON POST Request With HttpURLConnection](https://www.baeldung.com/httpurlconnection-post)
- [Using Curl in Java](https://www.baeldung.com/java-curl)
- [Do a Simple HTTP Request in Java](http://www.baeldung.com/java-http-request)
- [Sending Emails with Java](http://www.baeldung.com/java-email)
- [[<-- Prev]](/core-java-modules/core-java-networking)
@@ -0,0 +1,40 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>core-java-networking-2</artifactId>
<name>core-java-networking-2</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>${httpclient.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>${javax.mail.version}</version>
</dependency>
</dependencies>
<build>
<finalName>core-java-networking-2</finalName>
</build>
<properties>
<httpclient.version>4.5.9</httpclient.version>
<javax.mail.version>1.5.0-b01</javax.mail.version>
</properties>
</project>
@@ -0,0 +1,29 @@
package com.baeldung.curltojava;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
public class JavaCurlExamples {
public static String inputStreamToString(InputStream inputStream) {
final int bufferSize = 8 * 1024;
byte[] buffer = new byte[bufferSize];
final StringBuilder builder = new StringBuilder();
try (BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream, bufferSize)) {
while (bufferedInputStream.read(buffer) != -1) {
builder.append(new String(buffer));
}
} catch (IOException ex) {
Logger.getLogger(JavaCurlExamples.class.getName()).log(Level.SEVERE, null, ex);
}
return builder.toString();
}
public static void consumeInputStream(InputStream inputStream) {
inputStreamToString(inputStream);
}
}
@@ -0,0 +1,65 @@
package com.baeldung.httprequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.util.Iterator;
import java.util.List;
public class FullResponseBuilder {
public static String getFullResponse(HttpURLConnection con) throws IOException {
StringBuilder fullResponseBuilder = new StringBuilder();
fullResponseBuilder.append(con.getResponseCode())
.append(" ")
.append(con.getResponseMessage())
.append("\n");
con.getHeaderFields()
.entrySet()
.stream()
.filter(entry -> entry.getKey() != null)
.forEach(entry -> {
fullResponseBuilder.append(entry.getKey())
.append(": ");
List<String> headerValues = entry.getValue();
Iterator<String> it = headerValues.iterator();
if (it.hasNext()) {
fullResponseBuilder.append(it.next());
while (it.hasNext()) {
fullResponseBuilder.append(", ")
.append(it.next());
}
}
fullResponseBuilder.append("\n");
});
Reader streamReader = null;
if (con.getResponseCode() > 299) {
streamReader = new InputStreamReader(con.getErrorStream());
} else {
streamReader = new InputStreamReader(con.getInputStream());
}
BufferedReader in = new BufferedReader(streamReader);
String inputLine;
StringBuilder content = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
in.close();
fullResponseBuilder.append("Response: ")
.append(content);
return fullResponseBuilder.toString();
}
}
@@ -0,0 +1,21 @@
package com.baeldung.httprequest;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;
public class ParameterStringBuilder {
public static String getParamsString(Map<String, String> params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
for (Map.Entry<String, String> entry : params.entrySet()) {
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
result.append("&");
}
String resultString = result.toString();
return resultString.length() > 0 ? resultString.substring(0, resultString.length() - 1) : resultString;
}
}
@@ -0,0 +1,77 @@
package com.baeldung.mail;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.io.File;
import java.util.Properties;
public class EmailService {
private String host = "";
private int port = 0;
private String username = "";
private String password = "";
public EmailService(String host, int port, String username, String password) {
this.host = host;
this.port = port;
this.username = username;
this.password = password;
sendMail();
}
private void sendMail() {
Properties prop = new Properties();
prop.put("mail.smtp.auth", true);
prop.put("mail.smtp.starttls.enable", "true");
prop.put("mail.smtp.host", host);
prop.put("mail.smtp.port", port);
prop.put("mail.smtp.ssl.trust", host);
Session session = Session.getInstance(prop, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("from@gmail.com"));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("to@gmail.com"));
message.setSubject("Mail Subject");
String msg = "This is my first email using JavaMailer";
MimeBodyPart mimeBodyPart = new MimeBodyPart();
mimeBodyPart.setContent(msg, "text/html");
MimeBodyPart attachmentBodyPart = new MimeBodyPart();
attachmentBodyPart.attachFile(new File("pom.xml"));
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(mimeBodyPart);
multipart.addBodyPart(attachmentBodyPart);
message.setContent(multipart);
Transport.send(message);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String ... args) {
new EmailService("smtp.mailtrap.io", 25, "87ba3d9555fae8", "91cb4379af43ed");
}
}
@@ -0,0 +1,25 @@
package com.baeldung.url;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
public class UrlChecker {
public int getResponseCodeForURL(String address) throws IOException {
return getResponseCodeForURLUsing(address, "GET");
}
public int getResponseCodeForURLUsingHead(String address) throws IOException {
return getResponseCodeForURLUsing(address, "HEAD");
}
private int getResponseCodeForURLUsing(String address, String method) throws IOException {
HttpURLConnection.setFollowRedirects(false); // Set follow redirects to false
final URL url = new URL(address);
HttpURLConnection huc = (HttpURLConnection) url.openConnection();
huc.setRequestMethod(method);
return huc.getResponseCode();
}
}
@@ -0,0 +1,74 @@
package com.baeldung.url.auth;
import java.io.IOException;
import java.net.Authenticator;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.PasswordAuthentication;
import java.net.ProtocolException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import org.apache.commons.codec.binary.Base64;
public class HttpClient {
private final String user;
private final String password;
public HttpClient(String user, String password) {
this.user = user;
this.password = password;
}
public int sendRquestWithAuthHeader(String url) throws IOException {
HttpURLConnection connection = null;
try {
connection = createConnection(url);
connection.setRequestProperty("Authorization", createBasicAuthHeaderValue());
return connection.getResponseCode();
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
public int sendRquestWithAuthenticator(String url) throws IOException {
setAuthenticator();
HttpURLConnection connection = null;
try {
connection = createConnection(url);
return connection.getResponseCode();
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
private HttpURLConnection createConnection(String urlString) throws MalformedURLException, IOException, ProtocolException {
URL url = new URL(String.format(urlString));
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
return connection;
}
private String createBasicAuthHeaderValue() {
String auth = user + ":" + password;
byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(StandardCharsets.UTF_8));
String authHeaderValue = "Basic " + new String(encodedAuth);
return authHeaderValue;
}
private void setAuthenticator() {
Authenticator.setDefault(new BasicAuthenticator());
}
private final class BasicAuthenticator extends Authenticator {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, password.toCharArray());
}
}
}
@@ -0,0 +1,46 @@
package com.baeldung.urlconnection;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class PostJSONWithHttpURLConnection {
public static void main (String []args) throws IOException{
//Change the URL with any other publicly accessible POST resource, which accepts JSON request body
URL url = new URL ("https://reqres.in/api/users");
HttpURLConnection con = (HttpURLConnection)url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json; utf-8");
con.setRequestProperty("Accept", "application/json");
con.setDoOutput(true);
//JSON String need to be constructed for the specific resource.
//We may construct complex JSON using any third-party JSON libraries such as jackson or org.json
String jsonInputString = "{\"name\": \"Upendra\", \"job\": \"Programmer\"}";
try(OutputStream os = con.getOutputStream()){
byte[] input = jsonInputString.getBytes("utf-8");
os.write(input, 0, input.length);
}
int code = con.getResponseCode();
System.out.println(code);
try(BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "utf-8"))){
StringBuilder response = new StringBuilder();
String responseLine = null;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine.trim());
}
System.out.println(response.toString());
}
}
}
@@ -0,0 +1,50 @@
package com.baeldung.curltojava;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import org.junit.Assert;
import org.junit.Test;
public class JavaCurlExamplesLiveTest {
@Test
public void givenCommand_whenCalled_thenProduceZeroExitCode() throws IOException {
String command = "curl -X GET https://postman-echo.com/get?foo1=bar1&foo2=bar2";
ProcessBuilder processBuilder = new ProcessBuilder(command.split(" "));
processBuilder.directory(new File("/home/"));
Process process = processBuilder.start();
InputStream inputStream = process.getInputStream();
// Consume the inputStream so the process can exit
JavaCurlExamples.consumeInputStream(inputStream);
int exitCode = process.exitValue();
Assert.assertEquals(0, exitCode);
}
@Test
public void givenNewCommands_whenCalled_thenCheckIfIsAlive() throws IOException {
String command = "curl -X GET https://postman-echo.com/get?foo1=bar1&foo2=bar2";
ProcessBuilder processBuilder = new ProcessBuilder(command.split(" "));
processBuilder.directory(new File("/home/"));
Process process = processBuilder.start();
// Re-use processBuilder
processBuilder.command(new String[]{"newCommand", "arguments"});
Assert.assertEquals(true, process.isAlive());
}
@Test
public void whenRequestPost_thenCheckIfReturnContent() throws IOException {
String command = "curl -X POST https://postman-echo.com/post --data foo1=bar1&foo2=bar2";
Process process = Runtime.getRuntime().exec(command);
// Get the POST result
String content = JavaCurlExamples.inputStreamToString(process.getInputStream());
Assert.assertTrue(null != content && !content.isEmpty());
}
}
@@ -0,0 +1,184 @@
package com.baeldung.httprequest;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;
import java.io.*;
import java.net.CookieManager;
import java.net.HttpCookie;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class HttpRequestLiveTest {
@Test
public void whenGetRequest_thenOk() throws IOException {
URL url = new URL("http://example.com");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
Map<String, String> parameters = new HashMap<>();
parameters.put("param1", "val");
con.setDoOutput(true);
DataOutputStream out = new DataOutputStream(con.getOutputStream());
out.writeBytes(ParameterStringBuilder.getParamsString(parameters));
out.flush();
out.close();
con.setConnectTimeout(5000);
con.setReadTimeout(5000);
int status = con.getResponseCode();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuilder content = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
in.close();
assertEquals("status code incorrect", status, 200);
assertTrue("content incorrect", content.toString()
.contains("Example Domain"));
}
@Test
public void whenPostRequest_thenOk() throws IOException {
URL url = new URL("http://example.com");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json");
Map<String, String> parameters = new HashMap<>();
parameters.put("param1", "val");
con.setDoOutput(true);
DataOutputStream out = new DataOutputStream(con.getOutputStream());
out.writeBytes(ParameterStringBuilder.getParamsString(parameters));
out.flush();
out.close();
int status = con.getResponseCode();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuilder content = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
in.close();
assertEquals("status code incorrect", status, 200);
}
@Test
public void whenGetCookies_thenOk() throws IOException {
URL url = new URL("http://example.com");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
CookieManager cookieManager = new CookieManager();
String cookiesHeader = con.getHeaderField("Set-Cookie");
Optional<HttpCookie> usernameCookie = null;
if (cookiesHeader != null) {
List<HttpCookie> cookies = HttpCookie.parse(cookiesHeader);
cookies.forEach(cookie -> cookieManager.getCookieStore()
.add(null, cookie));
usernameCookie = cookies.stream()
.findAny()
.filter(cookie -> cookie.getName()
.equals("username"));
}
if (usernameCookie == null) {
cookieManager.getCookieStore()
.add(null, new HttpCookie("username", "john"));
}
con.disconnect();
con = (HttpURLConnection) url.openConnection();
con.setRequestProperty("Cookie", StringUtils.join(cookieManager.getCookieStore()
.getCookies(), ";"));
int status = con.getResponseCode();
assertEquals("status code incorrect", status, 200);
}
@Test
public void whenRedirect_thenOk() throws IOException {
URL url = new URL("http://example.com");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.setInstanceFollowRedirects(true);
int status = con.getResponseCode();
if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM) {
String location = con.getHeaderField("Location");
URL newUrl = new URL(location);
con = (HttpURLConnection) newUrl.openConnection();
}
assertEquals("status code incorrect", con.getResponseCode(), 200);
}
@Test
public void whenFailedRequest_thenOk() throws IOException {
URL url = new URL("http://example.com");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setConnectTimeout(5000);
con.setReadTimeout(5000);
int status = con.getResponseCode();
Reader streamReader = null;
if (status > 299) {
streamReader = new InputStreamReader(con.getErrorStream());
} else {
streamReader = new InputStreamReader(con.getInputStream());
}
BufferedReader in = new BufferedReader(streamReader);
String inputLine;
StringBuilder content = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
in.close();
con.disconnect();
assertEquals("status code incorrect", status, 411);
assertTrue("error content", content.toString()
.contains("411 - Length Required"));
}
@Test
public void whenGetRequestFullResponse_thenOk() throws IOException {
URL url = new URL("http://example.com");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.setConnectTimeout(5000);
con.setReadTimeout(5000);
String fullResponse = FullResponseBuilder.getFullResponse(con);
con.disconnect();
assertEquals("status code incorrect", con.getResponseCode(), 200);
assertTrue("header incorrect", fullResponse.contains("Content-Type: text/html; charset=UTF-8"));
assertTrue("response incorrect", fullResponse.contains("<!doctype html><html><head>"));
}
}
@@ -0,0 +1,39 @@
package com.baeldung.url;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.IOException;
import org.junit.Test;
public class UrlCheckerUnitTest {
@Test
public void givenValidUrl_WhenUsingHEAD_ThenReturn200() throws IOException {
UrlChecker tester = new UrlChecker();
int responseCode = tester.getResponseCodeForURLUsingHead("http://www.example.com");
assertEquals(200, responseCode);
}
@Test
public void givenInvalidIUrl_WhenUsingHEAD_ThenReturn404() throws IOException {
UrlChecker tester = new UrlChecker();
int responseCode = tester.getResponseCodeForURLUsingHead("http://www.example.com/unkownurl");
assertEquals(404, responseCode);
}
@Test
public void givenValidUrl_WhenUsingGET_ThenReturn200() throws IOException {
UrlChecker tester = new UrlChecker();
int responseCode = tester.getResponseCodeForURL("http://www.example.com");
assertEquals(200, responseCode);
}
@Test
public void givenInvalidIUrl_WhenUsingGET_ThenReturn404() throws IOException {
UrlChecker tester = new UrlChecker();
int responseCode = tester.getResponseCodeForURL("http://www.example.com/unkownurl");
assertEquals(404, responseCode);
}
}
@@ -0,0 +1,52 @@
package com.baeldung.url.auth;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class HttpClientUnitTest {
@Test
public void sendRquestWithAuthHeader() throws Exception {
HttpClient httpClient = new HttpClient("user1", "pass1");
int status = httpClient.sendRquestWithAuthHeader("https://httpbin.org/basic-auth/user1/pass1");
assertTrue(isSuccess(status));
}
@Test
public void sendRquestWithAuthHeader_whenIncorrectCredentials_thenNotSuccessful() throws Exception {
HttpClient httpClient = new HttpClient("John", "Smith");
int status = httpClient.sendRquestWithAuthHeader("https://httpbin.org/basic-auth/user1/pass1");
assertTrue(isUnauthorized(status));
}
@Test
public void sendRquestWithAuthenticator() throws Exception {
HttpClient httpClient = new HttpClient("user2", "pass2");
int status = httpClient.sendRquestWithAuthenticator("https://httpbin.org/basic-auth/user2/pass2");
assertTrue(isSuccess(status));
}
@Test
public void sendRquestWithAuthenticator_whenIncorrectCredentials_thenNotSuccessful() throws Exception {
HttpClient httpClient = new HttpClient("John", "Smith");
int status = httpClient.sendRquestWithAuthenticator("https://httpbin.org/basic-auth/user2/pass2");
assertTrue(isUnauthorized(status));
}
private boolean isSuccess(int status) {
return (status >= 200) && (status < 300);
}
private boolean isUnauthorized(int status) {
return status == 401;
}
}