Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android POST data with login details for php file - https

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
    }
}
like image 504
endofsource Avatar asked Jan 16 '12 09:01

endofsource


1 Answers

Try this:

HttpHost targetHost = new HttpHost(HOSTNAME, -1, SCHEME);
httpclient.getCredentialsProvider().setCredentials(
    new AuthScope(targetHost.getHostName(), targetHost.getPort()),
    new UsernamePasswordCredentials(USERNAME, PASSWORD)
);
like image 158
Francesco Vadicamo Avatar answered Nov 16 '22 19:11

Francesco Vadicamo