Android的,Java的:HTTP POST请求 [英] Android, Java: HTTP POST Request
问题描述
我必须做一个HTTP POST请求的Web服务进行身份验证的用户名和密码的用户。在Web服务的家伙给了我下面的信息来构建HTTP POST请求。
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
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[username@company.com]]></Rl>
<uid><![CDATA[3539145]]></uid>
<Rmu><![CDATA[f8e8917f7964d4cc7c4c4226f060e3ea]]></Rmu>
</login>
这是我在做什么HttpPost postRequest =新HttpPost(urlString);我如何构造参数的休息吗?
This is what i am doing HttpPost postRequest = new HttpPost(urlString); How do i construct the rest of the parameters?
推荐答案
下面是一个例子$ P $在的 androidsnippets.com (该网站目前没有维护了)。
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
}
所以,你可以为 <$ C $添加参数C> BasicNameValuePair </ code> 。
另一种方法是使用(HTTP)的URLConnection
。另请参见<一个href="http://stackoverflow.com/questions/2793150/how-to-use-java-net-urlconnection-to-fire-and-handle-http-requests">Using java.net.URLConnection中火和处理HTTP请求的。这实际上是在新的Android版本(姜饼+)的preferred方法。另请参见这个博客,<一个href="http://developer.android.com/about/versions/marshmallow/android-6.0-changes.html#behavior-apache-http-client"相对=nofollow>此开发文档和Android的 的HttpURLConnection
的javadoc 。
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.
这篇关于Android的,Java的:HTTP POST请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!