Skip to content

Instantly share code, notes, and snippets.

@guftall
Created January 28, 2018 12:38
Show Gist options
  • Save guftall/cf77877993661c7ba93c90189272f646 to your computer and use it in GitHub Desktop.
Save guftall/cf77877993661c7ba93c90189272f646 to your computer and use it in GitHub Desktop.
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.nio.file.Files;
public class Main {
public static void main(String[] args) throws IOException {
String url = "http://surlfpgu.eu-4.evennode.com/dev/api/client/account/profile/uploadpic";
String charset = "UTF-8";
String param = "8f205c6a5712a8b18ae95f0553e7e413f8d5b319fb7343f441cc73617626a5ab";
File binaryFile = new File("/home/guftall/Pictures/img1.jpg");
String boundary = Long.toHexString(System.currentTimeMillis()); // Just generate some unique random value.
String CRLF = "\r\n"; // Line separator required by multipart/form-data.
URLConnection connection = new URL(url).openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
connection.setRequestProperty("ls": param);
try (
OutputStream output = connection.getOutputStream();
PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, charset), true);
) {
// Send binary file.
writer.append("--" + boundary).append(CRLF);
writer.append("Content-Disposition: form-data; name=\"avatar\"; filename=\"" + binaryFile.getName() + "\"").append(CRLF);
writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(binaryFile.getName())).append(CRLF);
writer.append("Content-Transfer-Encoding: binary").append(CRLF);
writer.append(CRLF).flush();
Files.copy(binaryFile.toPath(), output);
output.flush(); // Important before continuing with writer!
writer.append(CRLF).flush(); // CRLF is important! It indicates end of boundary.
// End of multipart/form-data.
writer.append("--" + boundary + "--").append(CRLF).flush();
}
// Request is lazily fired whenever you need to obtain information about response.
int responseCode = ((HttpURLConnection) connection).getResponseCode();
System.out.println(responseCode); // Should be 200
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(((HttpURLConnection) connection).getInputStream()));
StringBuilder sBuilder = new StringBuilder();
String output;
while((output = bufferedReader.readLine()) != null) {
sBuilder.append(output);
}
System.out.println(sBuilder.toString());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment