Skip to content

Instantly share code, notes, and snippets.

@henrik242 henrik242/HttpStuff.java
Last active Mar 2, 2017

Embed
What would you like to do?
HTTP POST and GET in plain Java
import java.io.*;
import java.net.*;
import java.util.Scanner;
import static java.nio.charset.StandardCharsets.UTF_8;
public class HttpStuff {
public static void main(String[] args) throws IOException {
System.out.println(post("http://example.com/", "foo=bar&baz=moo"));
System.out.println(get("http://example.com/?stuff"));
}
static String post(String url, String content) throws IOException {
HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", String.valueOf(content.length()));
OutputStream os = conn.getOutputStream();
os.write(content.getBytes(UTF_8));
InputStream is = conn.getInputStream();
String result = convertStreamToString(is);
os.flush();
os.close();
is.close();
conn.disconnect();
return result;
}
static String get(String url) throws IOException {
HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
conn.setDoInput(true);
conn.setRequestMethod("GET");
InputStream is = conn.getInputStream();
String result = convertStreamToString(is);
is.close();
conn.disconnect();
return result;
}
static String convertStreamToString(InputStream is) {
Scanner s = new Scanner(is).useDelimiter("\\A");
return s.hasNext() ? s.next() : "";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.