1.1.34.2. fejezet, RestApi kliens

Byte tömb beolvasása HttpURLConnection-ről

package hu.infokristaly.restclient;
 
import java.io.DataInputStream;
import java.io.File;
import java.net.HttpURLConnection;
import java.net.URL;
 
import org.apache.commons.io.FileUtils;
 
public class RestApiClient {
 
	private static void sendGetRequest(String urlString) throws Exception {
		URL url = new URL(urlString);
		HttpURLConnection con = (HttpURLConnection) url.openConnection();
 
		con.setRequestMethod("GET");
		con.setRequestProperty("cache-control", "no-cache");
 
		DataInputStream ds = new DataInputStream(con.getInputStream());
		FileUtils.copyInputStreamToFile(ds, new File("/home/pzoli/temp.jar"));
	}
 
	private static void sendMultipartData() throws ClientProtocolException, IOException {
		//https://stackoverflow.com/questions/1378920/how-can-i-make-a-multipart-form-data-post-request-using-java
		CloseableHttpClient httpClient = HttpClients.createDefault();
		HttpPost uploadFile = new HttpPost("http://localhost:8080/fileinfo/fileupload");
		MultipartEntityBuilder builder = MultipartEntityBuilder.create();
		builder.addTextBody("field1", "yes", ContentType.TEXT_PLAIN);
 
		// This attaches the file to the POST:
		File f = new File("/home/pzoli/vpscalc2.jar");
		builder.addBinaryBody("file", new FileInputStream(f), ContentType.APPLICATION_OCTET_STREAM, f.getName());
 
		HttpEntity multipart = builder.build();
		System.out.println(multipart);
		uploadFile.setEntity(multipart);
		CloseableHttpResponse response = httpClient.execute(uploadFile);
		HttpEntity responseEntity = response.getEntity();
		System.out.println(response.getStatusLine().getStatusCode());
		System.out.println(responseEntity);
 
	}
 
	public static void main(String[] args) {
		try {
			sendGetRequest("http://localhost:8080/fileinfo/getById/1");
			sendMultipartData();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

pom.xml

<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>Homework4RestClient</groupId>
  <artifactId>Homework4RestClient</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <build>
    <sourceDirectory>src</sourceDirectory>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.8.1</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
    </plugins>
  </build>
  <dependencies>
  	<dependency>
  		<groupId>commons-io</groupId>
  		<artifactId>commons-io</artifactId>
  		<version>2.6</version>
  	</dependency>
  </dependencies>
</project>