PostRequest.java
Home
/
src /
main /
java /
br /
ufrgs /
inf /
prosoft /
requestssimulator /
requests /
PostRequest.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package br.ufrgs.inf.prosoft.requestssimulator.requests;
import br.ufrgs.inf.prosoft.requestssimulator.Session;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
/**
*
* @author romulo
*/
public class PostRequest extends Request {
private final String data;
protected PostRequest(RequestPlan requestPlan, Session session, String URL, String data) {
super(requestPlan, session, URL);
this.data = data;
}
protected PostRequest(RequestPlan requestPlan, Session session, String URL, String data, String headers) {
super(requestPlan, session, URL, headers);
this.data = data;
}
protected String getData() {
return this.data;
}
@Override
protected void fireRequest() {
HttpURLConnection httpURLConnection = null;
try {
String stringURL = fillPropertyVariable(getURL());
URL url = new URL(stringURL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
httpURLConnection = connection;
connection.setRequestMethod("POST");
headers().forEach(entry -> {
String value = fillPropertyVariable(entry.getValue());
connection.setRequestProperty(entry.getKey(), value);
});
connection.setDoOutput(true);
try (OutputStream outputStream = connection.getOutputStream()) {
outputStream.write(this.data.getBytes());
}
int responseCode = connection.getResponseCode();
if (responseCode < 400) {
Logger.getGlobal().log(Level.INFO, "{0} on {1} {2}", new Object[]{responseCode, getMethod(), stringURL});
try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
String response = bufferedReader.lines().collect(Collectors.joining());
processResponse(response);
}
} else {
Logger.getGlobal().log(Level.SEVERE, "error {0} on {1} {2}", new Object[]{responseCode, getMethod(), stringURL});
}
} catch (MalformedURLException ex) {
Logger.getGlobal().log(Level.SEVERE, "Malormed URL");
} catch (IOException ex) {
Logger.getGlobal().log(Level.SEVERE, "IOException");
} catch (Exception ex) {
ex.printStackTrace();
} finally {
if (httpURLConnection != null) {
httpURLConnection.disconnect();
}
}
}
}