我目前正在尝试通过Android将数据发布到我的网站。
我想要发送数据的php脚本需要登录...
通过浏览器,我可以使用登录数据,如下面的链接所示:
https://demo:demo@www.example.com/foo.php?bar=42
如果我尝试下面的代码一样没有任何反应:
public void postData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
String postUrl = "https://demo:demo@www.example.com/foo.php";
HttpPost httppost = new HttpPost(postUrl);
try {
// Add your data
List nameValuePairs = new ArrayList(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 - 需要授权”
不幸的是我不知道如何解决这个错误):
感谢“Francesco 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 nameValuePairs = new ArrayList(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
}
}