Android,Java:HTTP POST请求

我必须对Web服务执行http post请求,以用户名和密码对用户进行身份validation。 Web服务人员给了我下面的信息来构buildHTTP 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 

我将得到的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> 

这是我在做什么HttpPost postRequest = new HttpPost(urlString); 我如何构build其余的参数?

这是以前在androidsnippets.com上find的一个例子(该网站目前不再被维护)。

 // 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 } 

所以,你可以添加你的参数为BasicNameValuePair

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

到@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); } 

这里是convertStramToString的一个例子 。

请考虑使用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(); 

你将需要自己去捕捉exception。

尝试HttpClient for Java:

http://hc.apache.org/httpclient-3.x/

您可以重复使用我添加到ACRA的实施: http : //code.google.com/p/acra/source/browse/tags/REL-3_1_0/CrashReport/src/org/acra/HttpUtils.java? r= 236

(请参阅doPost(Map,Url)方法,使用http和https甚至使用自签名证书)

我使用下面的代码从我的Android客户端应用程序发送HTTP POST到我的服务器上的C#桌面应用程序:

 // 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#应用程序的请求(类似于Web服务器的小应用程序)。 我设法阅读请求发布的数据使用下面的代码:

 server = new HttpListener(); server.Prefixes.Add("http://*:50000/"); server.Start(); HttpListenerContext context = server.GetContext(); HttpListenerContext context = obj as HttpListenerContext; HttpListenerRequest request = context.Request; StreamReader sr = new StreamReader(request.InputStream); string str = sr.ReadToEnd(); 

我宁愿推荐你使用Volley来做GET,PUT,POST …请求。

首先,在您的gradle文件中添加依赖项。

compile 'com.he5ed.lib:volley:android-cts-5.1_r4'

现在,使用这个代码片段来发出请求。

 RequestQueue queue = Volley.newRequestQueue(getApplicationContext()); StringRequest postRequest = new StringRequest( com.android.volley.Request.Method.POST, mURL, new Response.Listener<String>() { @Override public void onResponse(String response) { // response Log.d("Response", response); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // error Log.d("Error.Response", error.toString()); } } ) { @Override protected Map<String, String> getParams() { Map<String, String> params = new HashMap<String, String>(); //add your parameters here as key-value pairs params.put("username", username); params.put("password", password); return params; } }; queue.add(postRequest);