Created
February 25, 2014 22:49
-
-
Save caseyscarborough/9219661 to your computer and use it in GitHub Desktop.
Example of get and post requests using Java.
This file contains hidden or 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.BufferedReader; | |
import java.io.DataOutputStream; | |
import java.io.InputStreamReader; | |
import java.net.HttpURLConnection; | |
import java.net.URL; | |
import javax.net.ssl.HttpsURLConnection; | |
public class HttpSender { | |
public static void main(String[] args) throws Exception { | |
HttpSender http = new HttpSender(); | |
http.getRequest("http://caseyscarborough.com"); | |
http.postRequest("https://selfsolve.apple.com/wcResults.do", "sn=C02G8416DRJM&cn=&locale=&caller=&num=12345"); | |
} | |
private void getRequest(String url) throws Exception { | |
URL obj = new URL(url); | |
HttpURLConnection conn = (HttpURLConnection) obj.openConnection(); | |
conn.setRequestMethod("GET"); | |
int responseCode = conn.getResponseCode(); | |
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); | |
String inputLine; | |
StringBuffer response = new StringBuffer(); | |
while ((inputLine = in.readLine()) != null) { response.append(inputLine); } | |
in.close(); | |
System.out.println(response.toString()); | |
} | |
private void postRequest(String url, String params) throws Exception { | |
URL obj = new URL(url); | |
HttpsURLConnection conn = (HttpsURLConnection) obj.openConnection(); | |
conn.setRequestMethod("POST"); | |
conn.setRequestProperty("Accept-Language", "en-US,en;q=0.5"); | |
conn.setDoOutput(true); | |
DataOutputStream wr = new DataOutputStream(conn.getOutputStream()); | |
wr.writeBytes(params); | |
wr.flush(); | |
wr.close(); | |
int responseCode = conn.getResponseCode(); | |
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); | |
String inputLine; | |
StringBuffer response = new StringBuffer(); | |
while ((inputLine = in.readLine()) != null) { response.append(inputLine); } | |
in.close(); | |
System.out.println(response.toString()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment