Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
202 views
in Technique[技术] by (71.8m points)

Android, Java: HTTP POST Request

I have to do a http post request to a web-service for authenticating the user with username and password. The Web-service guy gave me following information to construct HTTP Post request.

POST /login/dologin HTTP/1.1
Host: webservice.companyname.com
Content-Type: application/x-www-form-urlencoded
Content-Length: 48

id=username&num=password&remember=on&output=xml

The XML Response that i will be getting is

<?xml version="1.0" encoding="ISO-8859-1"?>
<login>
 <message><![CDATA[]]></message>
 <status><![CDATA[true]]></status>
 <Rlo><![CDATA[Username]]></Rlo>
 <Rsc><![CDATA[9L99PK1KGKSkfMbcsxvkF0S0UoldJ0SU]]></Rsc>
 <Rm><![CDATA[b59031b85bb127661105765722cd3531==AO1YjN5QDM5ITM]]></Rm>
 <Rl><![CDATA[[email protected]]]></Rl>
 <uid><![CDATA[3539145]]></uid>
 <Rmu><![CDATA[f8e8917f7964d4cc7c4c4226f060e3ea]]></Rmu>
</login>

This is what i am doing HttpPost postRequest = new HttpPost(urlString); How do i construct the rest of the parameters?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Here's an example previously found at androidsnippets.com (the site is currently not maintained anymore).

// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");

try {
    // Add your data
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
    nameValuePairs.add(new BasicNameValuePair("id", "12345"));
    nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!"));
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

    // Execute HTTP Post Request
    HttpResponse response = httpclient.execute(httppost);

} catch (ClientProtocolException e) {
    // TODO Auto-generated catch block
} catch (IOException e) {
    // TODO Auto-generated catch block
}

So, you can add your parameters as BasicNameValuePair.

An alternative is to use (Http)URLConnection. See also Using java.net.URLConnection to fire and handle HTTP requests. This is actually the preferred method in newer Android versions (Gingerbread+). See also this blog, this developer doc and Android's HttpURLConnection javadoc.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...