2012-01-16 27 views
6

Tôi hiện đang cố gắng đăng dữ liệu qua Android đến trang web của mình.Dữ liệu POST của Android với chi tiết đăng nhập cho tệp php - https

Các kịch bản php Tôi muốn gửi dữ liệu đến nhu cầu đăng nhập ...

Via trình duyệt tôi có thể sử dụng dữ liệu đăng nhập như trong liên kết hiển thị dưới đây:

https://demo:[email protected]/foo.php?bar=42

Nếu tôi cố gắng cùng với đoạn mã sau có gì xảy ra:

public void postData() { 

    // Create a new HttpClient and Post Header 
    HttpClient httpclient = new DefaultHttpClient(); 
    String postUrl = "https://demo:[email protected]/foo.php"; 
    HttpPost httppost = new HttpPost(postUrl); 
    try { 

     // Add your data 
     List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); 
     nameValuePairs.add(new BasicNameValuePair("bar", "42")); 
     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 lỗi duy nhất tôi có được/câu trả lời:

"401 - Authorization Required"

Đáng tiếc là tôi không biết làm thế nào để khắc phục lỗi đó):

Nhờ "Francesco Vadicamo" mã làm việc:

public void postData() { 
    // Create a new HttpClient and Post Header 
    DefaultHttpClient httpclient = new DefaultHttpClient(); 
    String postUrl = "https://www.example.com/foo.php"; 


    HttpHost targetHost = new HttpHost("www.example.com", -1, "https"); 

    httpclient.getCredentialsProvider().setCredentials(
      new AuthScope(targetHost.getHostName(), targetHost.getPort()), 
      new UsernamePasswordCredentials("demo", "demo")); 
    HttpPost httppost = new HttpPost(postUrl); 
    try { 

     // Add your data 
     List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); 
     nameValuePairs.add(new BasicNameValuePair("bar", "42")); 
     httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 

     // Execute HTTP Post Request 
     HttpResponse response = httpclient.execute(targetHost, httppost); 
    } catch (ClientProtocolException e) { 
     // TODO Auto-generated catch block 
    } catch (IOException e) { 
     // TODO Auto-generated catch block 
    } 
} 

Trả lời

3

Hãy thử điều này:

HttpHost targetHost = new HttpHost(HOSTNAME, -1, SCHEME); 
httpclient.getCredentialsProvider().setCredentials(
    new AuthScope(targetHost.getHostName(), targetHost.getPort()), 
    new UsernamePasswordCredentials(USERNAME, PASSWORD) 
); 
+0

Cảm ơn người đàn ông. Hoạt động tốt (: – endofsource

+0

@EndOfSource: Vui lòng, bạn có thể đặt làm câu trả lời không? –

+0

Xong - tôi đoán vậy. – endofsource

Các vấn đề liên quan