HttpURLConnection con;
String url;
HttpReq() {
}
HttpReq(String url) throws IOException {
this.url = url;
URL myurl = new URL(url);
con = (HttpURLConnection) myurl.openConnection();
}
void closeServer() {
con.disconnect();
}
public StringBuilder get() throws IOException {
StringBuilder content;
con.setRequestMethod("GET");
try (BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()))) {
String line;
content = new StringBuilder();
while ((line = in.readLine()) != null) {
content.append(line);
content.append(System.lineSeparator());
}
}
System.out.println(content.toString());
return content;
}
public StringBuilder post() throws IOException {
String urlParameters = "name=Jack&occupation=programmer";
StringBuilder content;
byte[] postData = urlParameters.getBytes(StandardCharsets.UTF_8);
con.setDoOutput(true);
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", "Java client");
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
try (DataOutputStream wr = new DataOutputStream(con.getOutputStream())) {
wr.write(postData);
}
try (BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()))) {
String line;
content = new StringBuilder();
while ((line = in.readLine()) != null) {
content.append(line);
content.append(System.lineSeparator());
}
}
System.out.println(content.toString());
return content;
}