Android POST data with login details for php file - https

I am currently trying to transfer POST data via Android to my website.

PHP script I want to send login information ...

Through the browser, I can use the login information as shown in the link below:

https: // demo: demo@www.example.com /foo.php?bar=42

If I try to do the same with the following code, nothing will happen:

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<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 / response is:

"401 - Authorization Required"

Unfortunately, I do not know how to fix this error):

Thanks to the working code of "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<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 } } 
+6
source share
1 answer

Try the following:

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

Source: https://habr.com/ru/post/906085/


All Articles