Created
September 21, 2011 15:15
-
-
Save avargas/1232324 to your computer and use it in GitHub Desktop.
java posting example
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.InputStreamReader; | |
import java.io.OutputStreamWriter; | |
import java.net.URLConnection; | |
import java.net.URLEncoder; | |
import java.net.URL; | |
import java.util.Hashtable; | |
import java.util.Map; | |
import java.util.Iterator; | |
class Test | |
{ | |
public static void main (String args[]) | |
{ | |
try { | |
System.out.println("requesting the URL"); | |
// construct the arguments we"re going to post | |
Hashtable<String, String> opts = new Hashtable<String, String>(); | |
opts.put("facebook_token", "123"); | |
opts.put("another", "yes"); | |
// construct the raw | |
String raw = new String(); | |
Iterator<Map.Entry<String, String>> it = opts.entrySet().iterator(); | |
while (it.hasNext()) { | |
Map.Entry<String, String> entry = it.next(); | |
raw = raw + entry.getKey() + "=" + URLEncoder.encode(entry.getValue(), "UTF-8") + "&"; | |
} | |
System.out.println("generated post arguments is " + raw + "\n\n\n"); | |
// now, request the url | |
URL url = new URL("http://okc1-dev1.stormwest.com/post-get-test.php"); | |
URLConnection conn = url.openConnection(); | |
conn.setDoOutput(true); | |
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); | |
wr.write(raw); | |
wr.flush(); | |
// read response back | |
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); | |
String line; | |
while ((line = rd.readLine()) != null) { | |
System.out.println("got " + line); | |
} | |
wr.close(); | |
rd.close(); | |
} catch (Exception e) { | |
System.err.print(e.toString()); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment