Last active
March 2, 2017 12:07
-
-
Save henrik242/5c22b6bf23d81ccbfac9c447694e5d65 to your computer and use it in GitHub Desktop.
HTTP POST and GET in plain Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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