cz.mmsparams.api.http.HttpPostUtil Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of MmsParamsAPI Show documentation
Show all versions of MmsParamsAPI Show documentation
Common library for MmsParams system
The newest version!
package cz.mmsparams.api.http;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.annotation.Nonnull;
import cz.mmsparams.api.logging.APILoggerFactory;
import cz.mmsparams.api.logging.ApiLogFacade;
import cz.mmsparams.api.logging.ILogger;
import cz.mmsparams.api.utils.LogUtil;
public class HttpPostUtil
{
private static final ILogger LOGGER = APILoggerFactory.getLogger(HttpPostUtil.class);
private HttpPostUtil()
{
}
@Nonnull
public static TaskResult postData(String urlAddress, String data)
{
HttpURLConnection conn = null;
try
{
final URL url = new URL(urlAddress);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
conn.setRequestProperty("Accept", "application/json");
conn.setDoOutput(true);
conn.setDoInput(true);
int timeout = 5000;
conn.setConnectTimeout(timeout);
conn.setReadTimeout(timeout);
DataOutputStream os = new DataOutputStream(conn.getOutputStream());
os.writeBytes(data);
os.flush();
final int status = conn.getResponseCode();
switch (status)
{
case 200:
case 201:
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null)
{
sb.append(line).append(LogUtil.NEW_LINE);
}
br.close();
return new TaskResult<>(sb.toString());
default:
return new TaskResult<>(new Exception("Invalid status code: " + status));
}
}
catch (Exception e)
{
ApiLogFacade.logEx(LOGGER, "postData", e);
return new TaskResult<>(e);
}
finally
{
if (conn != null)
{
try
{
conn.disconnect();
}
catch (Exception ex)
{
ApiLogFacade.logEx(LOGGER, "getDataFromUrl", ex);
}
}
}
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy