2010-12-28 6 views
40

Tôi phải thực hiện yêu cầu đăng http lên dịch vụ web để xác thực người dùng bằng tên người dùng và mật khẩu. Anh chàng dịch vụ web đã cho tôi thông tin sau để xây dựng yêu cầu HTTP Post.Android, Java: Yêu cầu POST HTTP

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 

Phản ứng XML mà tôi sẽ được nhận là

<?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> 

Đây là những gì tôi đang làm HttpPost postRequest = new HttpPost (urlString); Làm thế nào để tôi xây dựng phần còn lại của các tham số?

Trả lời

81

Đây là một ví dụ được tìm thấy trước đây tại androidsnippets.com (trang web hiện không được duy trì nữa).

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

Vì vậy, bạn có thể thêm tham số của mình là BasicNameValuePair.

Cách khác là sử dụng (Http)URLConnection. Xem thêm Using java.net.URLConnection to fire and handle HTTP requests. Đây thực sự là phương pháp ưa thích trong các phiên bản Android mới hơn (Gingerbread +). Xem thêm this blog, this developer docHttpURLConnection javadoc của Android.

+1

Có cách nào dễ dàng để thêm mảng không? Bạn sẽ phải lặp qua chúng và thêm cặp BasicNameValuePair ("mảng []", mảng [i])? – gsingh2011

+1

Nó cũng có hiệu quả trên các tệp JSON thay vì trong XML? –

+2

Đối với Android 2.3 trở lên, Google khuyên bạn sử dụng HttpURLConnection. http://developer.android.com/reference/org/apache/http/impl/client/DefaultHttpClient.html –

0

Hãy thử HttpClient cho Java:

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

+1

Bạn đã bỏ lỡ thẻ 'Android' chưa? Nó đã được sử dụng (một phiên bản lite của) HttpClient dưới nắp! Xem thêm [HttpPost javadoc] (http://developer.android.com/reference/org/apache/http/client/methods/HttpPost.html). – BalusC

2

Hãy xem xét sử dụng HttpPost. Áp dụng điều này: 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(); 

Bạn sẽ cần phải tự mình loại trừ ngoại lệ.

+0

Làm cách nào để in phản hồi? – Tamil

5

để @BalusC câu trả lời Tôi sẽ thêm cách chuyển đổi phản hồi trong một Chuỗi:

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

Here is an example of convertStramToString.

0

tôi đã sử dụng đoạn mã sau để gửi HTTP POST từ ứng dụng client android của tôi để C# ứng dụng desktop trên máy chủ của tôi:

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

tôi làm việc trên đọc yêu cầu từ một ứng dụng C# trên máy chủ của tôi (một cái gì đó giống như một ứng dụng máy chủ web nhỏ). Tôi cố gắng đọc yêu cầu gửi dữ liệu bằng cách sử dụng đoạn mã sau:

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(); 
1

Tôi muốn khuyên bạn nên sử dụng Volley để làm GET, PUT, POST ... yêu cầu.

Đầu tiên, thêm phụ thuộc vào tệp gradle của bạn.

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

Bây giờ, sử dụng đoạn mã này để đưa ra yêu cầu.

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);