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
}
}
謝謝你。工作正常(: – endofsource 2012-01-16 10:45:36
@EndOfSource:請,你可以設置爲回答? – 2012-01-16 10:54:43
完成 - 我猜。 – endofsource 2012-01-16 11:09:52