Skip to content

Instantly share code, notes, and snippets.

@scrouthtv
Created July 30, 2018 12:07
Show Gist options
  • Save scrouthtv/818eed3899bc5c70a6a860f490aec7df to your computer and use it in GitHub Desktop.
Save scrouthtv/818eed3899bc5c70a6a860f490aec7df to your computer and use it in GitHub Desktop.
Basic post http request for java
package main;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
public class WebInteraction {
public static void main(String[] args) {
try {
String body = "q=getShops";
URL url = new URL("http://127.0.0.1/ShoppingList/api/request.php");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", String.valueOf(body.length()));
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
writer.write(body);
writer.flush();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
for(String line; (line = reader.readLine()) != null;)
System.out.println(line);
writer.close();
reader.close();
} catch (IOException ex) {
System.out.println("Exception whilst sending web request: ");
ex.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment