Connect to php page using .htaccess with android a

2019-07-12 02:38发布

问题:

i've a locked php page (username and password) by .htaccess file, how can i do to connect to this php with my android application? My function to connect is :

String conn(JSONObject json,String page){
        String result = "";
         String stringaFinale = "";
         InputStream is = null;

         final int TIMEOUT_MILLISEC = 5000;  // = 10 seconds    
        HttpParams httpParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT_MILLISEC);
        HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
        HttpClient client = new DefaultHttpClient(httpParams);

        HttpPost request = new HttpPost("http://olbolb.org/Hihi/"+page);

        //request result type
        request.setHeader("Accept", "application/json; charset=utf-8");

      try{  StringEntity se = new StringEntity(json.toString());
           se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json"));
           request.setEntity(se);      

           HttpResponse response = client.execute(request); 

            temp= EntityUtils.toString(response.getEntity());
            return temp;

      }
      catch(Exception e){ 
          return null; 

      }
    }

回答1:

You can add this code for BASIC authentication in HttpPost object:

HttpPost request = new HttpPost("http://olbolb.org/Hihi/"+page);
request.setHeader("Authorization", "Basic " + 
   new Base64().encodeToString("username:password".getBytes("UTF-8"), Base64.DEFAULT) );