2012-01-16 67 views
6

我目前正在尝试通过Android发布数据到我的网站。Android POST数据与登录详细信息的PHP文件 - https

PHP脚本我想将数据发送到需要登录...

通过浏览器,我可以使用的登录数据,如在链接如下图所示:

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

,如果我尝试相同用下面的代码没有任何反应:

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

唯一的错误我得到/响应:

“401 - 需要授权”

不幸的是,我不知道如何解决这个错误):

感谢 “弗朗切斯科Vadicamo” 工作代码:

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

回答

3

试试这个:

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

谢谢你。工作正常(: – endofsource 2012-01-16 10:45:36

+0

@EndOfSource:请,你可以设置为回答? – 2012-01-16 10:54:43

+0

完成 - 我猜。 – endofsource 2012-01-16 11:09:52