I'm currently trying to POST data via Android to my website.
The php script I want send data to needs a login...
Via browser I can use login data like in the link shown below:
https://demo:[email protected]/foo.php?bar=42
If i try the same with the following code nothing happens:
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
}
}
The only error i get / the response:
"401 - Authorization Required"
Unfortunately I don't know how to fix that error ):
Thanks to "Francesco Vadicamo" working code:
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
}
}
Try this:
HttpHost targetHost = new HttpHost(HOSTNAME, -1, SCHEME);
httpclient.getCredentialsProvider().setCredentials(
new AuthScope(targetHost.getHostName(), targetHost.getPort()),
new UsernamePasswordCredentials(USERNAME, PASSWORD)
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With