Android,Java:HTTP POST请求

Fah*_*kar 43 java android http-post

我必须向Web服务发出http post请求,以使用用户名和密码对用户进行身份验证.网络服务人员给了我以下信息来构建HTTP Post请求.

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
Run Code Online (Sandbox Code Playgroud)

我将获得的XML响应是

<?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>
Run Code Online (Sandbox Code Playgroud)

这就是我正在做的HttpPost postRequest = new HttpPost(urlString); 我如何构建其余参数?

Bal*_*usC 84

以下是先前在androidsnippets.com上发现的示例(该网站目前尚未维护).

// 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
}
Run Code Online (Sandbox Code Playgroud)

因此,您可以将参数添加为BasicNameValuePair.

另一种方法是使用(Http)URLConnection.另请参阅使用java.net.URLConnection触发和处理HTTP请求.这实际上是较新的Android版本(Gingerbread +)中的首选方法.另请参阅此博客,此开发人员文档和Android的HttpURLConnectionjavadoc.

  • 对于Android 2.3及更高版本,Google建议使用HttpURLConnection.http://developer.android.com/reference/org/apache/http/impl/client/DefaultHttpClient.html (2认同)

Fab*_* PH 6

到@BalusC回答我会添加如何在String中转换响应:

HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
if (entity != null) {
    InputStream instream = entity.getContent();

    String result = RestClient.convertStreamToString(instream);
    Log.i("Read from server", result);
}
Run Code Online (Sandbox Code Playgroud)

以下是convertStramToString的示例.


gig*_*dot 5

请考虑使用 HttpPost。从这里采用:http : //www.javaworld.com/javatips/jw-javatip34.html

URLConnection connection = new URL("http://webservice.companyname.com/login/dologin").openConnection();
// Http Method becomes POST
connection.setDoOutput(true);

// Encode according to application/x-www-form-urlencoded specification
String content =
    "id=" + URLEncoder.encode ("username") +
    "&num=" + URLEncoder.encode ("password") +
    "&remember=" + URLEncoder.encode ("on") +
    "&output=" + URLEncoder.encode ("xml");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 

// Try this should be the length of you content.
// it is not neccessary equal to 48. 
// content.getBytes().length is not neccessarily equal to content.length() if the String contains non ASCII characters.
connection.setRequestProperty("Content-Length", content.getBytes().length); 

// Write body
OutputStream output = connection.getOutputStream(); 
output.write(content.getBytes());
output.close();
Run Code Online (Sandbox Code Playgroud)

您需要自己捕获异常。