mysample.MySamplePort webservice = new mysample.MySamplePort();
webservice.inputHttpHeaders_x = new Map<String, String>();
Looking at line two above, what we have done is instantiated the input header map on our web service. From here we can add standard or custom headers.
Step 2: Basic Authentication Primer
Next you need to create a Basic Authentication HTTP header. This header takes a name/value pair that takes a user name and password in a base64 encoded string.
First thing you need to do is set the correct format for your username and password (which is going to become the value in your name/value pair after a little configuration)
Then take this string and convert it to base64. You can use a site such as Base64 Encoder if you need a quick way to do the conversion. In our example above the encoded string of myusername:mypassword looks like the following after encoding:
Step3: Add the Authentication Header
Now that we have our encoded string, we need to add the Authentication header to our webservice. Set the value in the name/value pair to Authorization and complete the value like below:
Last this is to put it all together, and add the Basic Authentication Header to our input headers:
webservice.inputHttpHeaders_x.put('Authorization', 'Basic bXl1c2VybmFtZTpteXBhc3N3b3Jk');
That's it! You just wrote your first Apex web service call using basic authentication. This was just a very brief introduction to HTTP authentication and web services. If you are looking for more information check out the online Apex docs and the many HTTP Authentication primers on the web.