hi all
i want to make an HttpURLConnection with POST data
this code works for the most part, except for the post data part
i tested it on this page, with this post data, with this command line in windows command prompt:
>java UrlToString http://mw3dailymedia.com/twixtor/javagrab.php user=chopficaro^
&pass=omgtkkyb
the ^ is required to escape the & in windows command prompt
and it returned to me
no username or password
i am absolutely sure that the php is correct, i can access this page with the user name and password specified with an html form
if it were the wrong username or password it would return "wrong user name or password"
so it did not send the post data.
why?
//takes am address, and post data, and returns the html as a string import java.net.*; import java.io.*; import java.lang.*; public class UrlToString { public String returnString = ""; public static void main (String[] args) throws Exception { //enter url and post data in cmd prompt to test UrlToString urlToString = new UrlToString (args[0],args[1]); System.out.println(urlToString.returnString); } //paramaters of returned string, address to get it from, and post data in th for of variable1=value1&variable2=value2... UrlToString (String inAddr, String rawData) throws Exception { //connection variables String agent = "Mozilla/4.0"; String type = "application/x-www-form-urlencoded"; HttpURLConnection connection = null; String encodedData = URLEncoder.encode( rawData, "UTF-8"); //connect try { URL searchUrl = new URL(inAddr); connection = (HttpURLConnection)searchUrl.openConnection(); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setRequestProperty( "User-Agent", agent ); connection.setRequestProperty( "Content-Type", type ); connection.setRequestProperty( "Content-Length", Integer.toString(encodedData.length()) ); OutputStream os = connection.getOutputStream(); os.write( encodedData.getBytes() ); os.flush(); os.close(); //check if theres an http error int rc = connection.getResponseCode(); if(rc==200) { //no http response code error //read the result from the server InputStreamReader in = new InputStreamReader(connection.getInputStream()); BufferedReader br = new BufferedReader(in); String strLine; //Read File Line By Line while ((strLine = br.readLine()) != null) { returnString = returnString.concat(strLine); } return; } else { System.out.println("http response code error: "+rc+"\n"); return; } } catch( IOException e ) { System.out.println("search URL connect failed: " + e.getMessage()); e.printStackTrace(); } } }