Skip to content

Instantly share code, notes, and snippets.

@moh-sushi
Last active December 14, 2020 00:36
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save moh-sushi/87655152f4f61d410a154c08159109dd to your computer and use it in GitHub Desktop.
Save moh-sushi/87655152f4f61d410a154c08159109dd to your computer and use it in GitHub Desktop.
jodd issue #437 - code snippet for downloading a zip file with jodd-http
import jodd.http.HttpRequest;
import jodd.http.HttpResponse;
import jodd.http.ProxyInfo;
import jodd.http.net.SocketHttpConnectionProvider;
import jodd.io.FileUtil;
import org.junit.Assert;
import org.junit.Test;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
/**
* code snippet for https://github.com/oblac/jodd/issues/437
*/
public class Jodd_Issue_437 {
@Test
public void test() throws Exception {
// jar & md5 hash from http://repo1.maven.org/maven2/org/jodd/jodd-http/3.9.1/
final String link = "https://repo1.maven.org/maven2/org/jodd/jodd-http/3.9.1/jodd-http-3.9.1.jar";
final String md5 = "e25844c8b7f1e5432cb3632c720f3aaa";
SocketHttpConnectionProvider socketHttpConnectionProvider = new SocketHttpConnectionProvider();
// use proxy configuration if neccessary
socketHttpConnectionProvider.useProxy(ProxyInfo.httpProxy("127.0.0.1", 8123, null, null));
HttpResponse response = HttpRequest
.get(link)
.withConnectionProvider(socketHttpConnectionProvider)
.charset("UTF-8")
.header("Content-type", "application/zip")
.send();
// ATTENTION : This saves the whole response, not just the body
// Thanx to igr@jodd.org for clarification
{
File zipFile = new File(System.getProperty("user.home"), "jodd-http-3.9.1.jar.zip");
FileUtil.deleteFile(zipFile);
try (OutputStream outputStream = new FileOutputStream(zipFile)) {
response.sendTo(outputStream);
}
// check md5 hash against expected one
final String actual_md5 = FileUtil.md5(zipFile);
// as mentioned above the md5 hashes may NOT be equals!
Assert.assertNotEquals(md5.toLowerCase(), actual_md5.toLowerCase() );
}
{
// collect raw body bytes
byte[] rawBytes = response.bodyBytes();
File zipFile = new File(System.getProperty("user.home"), "jodd-http-3.9.1.jar.zip");
FileUtil.deleteFile(zipFile);
FileUtil.writeBytes(zipFile, rawBytes);
// check md5 hash against expected one
final String actual_md5 = FileUtil.md5(zipFile);
Assert.assertEquals(md5.toLowerCase(), actual_md5.toLowerCase());
}
}
}
@igr
Copy link

igr commented Oct 9, 2017

Note that #1 saves the whole response, not just the body.

@moh-sushi
Copy link
Author

moh-sushi commented Oct 10, 2017

Hi @igr,

thank for clarification.

I have updated the code snippet...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment