Wednesday, September 14, 2011

[android-developers] Re: HttpURLConnection with POST method

Thank you so much for sharing that link... it helped me a great deal.
I wound up combining parts of that code with others to come up with
this:

/* Note: these are some methods in a class I wrote. "mURLString" is
the url to
* talk to such as "http://somesite/somefile.php"; "parameters" are the
parameters to use for the POST, such
* as "param1=abc&param2=def&param3=ghi". I create the string in
similar way to his example which was like:
*
* String parameters = "param1=" +
URLEncoder.encode("abc","UTF-8")+
* "&param2="+URLEncoder.encode("def","UTF-8")+
* "&param3="+URLEncoder.encode("ghi","UTF-8");
*
* The result of the POST is returned in "resultString".
*/

public String doHttpPost( String parameters )
{
String resultString = null;

URL url = null;
HttpURLConnection urlConnection = null;

try {
url = new URL( mURLString );
} catch (MalformedURLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}

try {
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setRequestMethod("POST");

urlConnection.setFixedLengthStreamingMode(parameters.getBytes().length);

//send the POST out
PrintWriter out = new PrintWriter(urlConnection.getOutputStream());
out.print(parameters);
out.close();

int response = urlConnection.getResponseCode();
// if resonse = HttpURLConnection.HTTP_OK = 200, then it worked.

InputStream in = new
BufferedInputStream(urlConnection.getInputStream());
resultString = readStream(in);

} catch( Exception e ){
e.printStackTrace();
}
finally {
urlConnection.disconnect();
}

return resultString;
}

public static String readStream(InputStream in) throws IOException
{
StringBuilder sb = new StringBuilder();
BufferedReader r = new BufferedReader(new InputStreamReader(in),
1000);

for (String line = r.readLine(); line != null; line = r.readLine())
{
sb.append(line).append("\n");
}

in.close();

return sb.toString();
}


On Aug 30, 1:06 pm, jesb <budiat...@gmail.com> wrote:
> i figured it out.http://digitallibraryworld.com/?p=189
>
> On Aug 16, 3:21 pm, lbendlin <l...@bendlin.us> wrote:
>
> >POSTworks very different from GET. You need to spend much more energy to
> > format the request body. You're missing the whole Content-Disposition:
> > form-data  and the delimiter definitions etc.
>
> > your out.write should then use the prepared request body string (as you did,
> > sort of).
>
>

--
You received this message because you are subscribed to the Google
Groups "Android Developers" group.
To post to this group, send email to android-developers@googlegroups.com
To unsubscribe from this group, send email to
android-developers+unsubscribe@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/android-developers?hl=en

No comments:

Post a Comment