Created
July 30, 2018 12:07
-
-
Save scrouthtv/818eed3899bc5c70a6a860f490aec7df to your computer and use it in GitHub Desktop.
Basic post http request for 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
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