Where did you get your accessToken from? If you used OAuth to establish the session then you will need to have the web
OAuth scope to use the sessionid for what is essentially a screen scraping web request. Having the api
scope would be sufficient for the Partner API, but for for mocking UI requests.

Other than that, as you have found, you need to put the sessionId/accessToken into a sid
cookie along with the request.
You can check your OAuth Scopes under
Setup > App Setup > Create > Apps > [App Name].
It should appear next to Selected OAuth Scopes.
When calling /services/oauth2/authorize
I'm using response_type=Token
. I'm also passing a scope query string parameter that includes web
. So I've specified the web scope on both the App and when initiating the OAuth process.
It appears you are using the Web Server OAuth Authentication Flow (based on the response_type=code). The scope parameter is applicable here as well.
scope
Specifies what data your application can access. See “Scope Parameter Values” in the online help for more information.
So you try modifying the authUrl line:
authUrl = environment + "/services/oauth2/authorize?response_type=code&client_id=" + clientId +
"&redirect_uri=" + URLEncoder.encode(redirectUri, "UTF-8") +
"&scope=full%20web";
Once you have a sessionId/accessToken, you can verify that it is valid for a web session in a browser using
https://<instanceUrl>/secur/frontdoor.jsp?sid=<accessToken>"
This should bounce you into a browser session with the sid cookie set. If it doesn't work, the session isn't valid for the web, which you will need to screenscrape an image via servlet/rtaImage
.
Final solution (By @GoldenAxe), that is only an example to check that the image fetching is working correctly, of-course it can be done much neatly.
In the WelcomeServlet.doGet:
String accessToken = (String) request.getSession().getAttribute(ACCESS_TOKEN);
String apiEndPoint = (String) request.getSession().getAttribute(INSTANCE_URL);
CookieManager cookieManager = new CookieManager();
cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
CookieHandler.setDefault(cookieManager);
URL url = null;
try
{
url = new URL(apiEndPoint + "/secur/frontdoor.jsp?sid=" + accessToken);
// open's a connection with the url specified and returns URLConnection object
URLConnection urlConnection = url.openConnection();
// get's the contents from this url specifies
urlConnection.getContent();
}
catch (MalformedURLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
String sid = "";
// returns the cookie store(bunch of cookies)
CookieStore cookieStore = cookieManager.getCookieStore();
// getting cookies which returns in the form of List of type HttpCookie
List<HttpCookie> listOfcookies = cookieStore.getCookies();
for (HttpCookie httpCookie : listOfcookies)
{
System.out.println("Cookie Name : " + httpCookie.getName() + " Cookie Value : " + httpCookie.getValue());
if (httpCookie.getName().compareTo("sid") == 0)
{
sid = httpCookie.getValue();
}
}
String urlString = "https://c.eu0.content.force.com/servlet/rtaImage?eid=ka3200000004MwH&feoid=00N20000008fSIK&refid=0EM20000000TzfR";
HttpClient client = new HttpClient();
GetMethod method = new GetMethod();
method.setRequestHeader("Cookie", "sid=" + sid);
method.setURI(new URI(urlString, true));
int returnCode = client.executeMethod(method);
if (returnCode != HttpStatus.SC_OK)
{
System.err.println("Unable to fetch image, status code: " + returnCode);
}
InputStream imageData = method.getResponseBodyAsStream();
OutputStream out = new BufferedOutputStream(new FileOutputStream("test-image.jpg"));
for (int i; (i = imageData.read()) != -1;)
{
out.write(i);
}
imageData.close();
out.close();
method.releaseConnection();
Have you read this: https://developer.salesforce.com/page/Digging_Deeper_into_OAuth_2.0_on_Force.com - best article on oAuth out there IMHO.
It discusses all available options. If not listed there then it will not be possible.
Now, if you do not have a way in the external system to have a user authenticate, you could build a visual force page for a user to authenticate and then grab the token. You could then provide the access and refresh token to the external system.
You would need to create a connected app and provide those details to the external system as well...
Doing this will allow the user to be able to revoke the token as needed and negate the need for the external system to store a password. Of course this assumes that the external system has properly implemented oAuth
Best Answer
It would appear that the first referenced example using the generated SoapBindingStub is a basic import of the Partner API. Using an Ant build script, the Partner WSDL and Apache Axis you generate proxy classes that can be used to invoke the API.
The second example appears to create a richer set of generated Java classes for accessing the SOAP web services and Bulk API. I can see classes such as a SessionRenewer and Base64 that indicate extended features and support that you wouldn't get with Apache Axis.
I'd say use the first approach if you just want basic access to the Partner API from java. The second is an option if you need access to more than just the Partner API and extended features such as a session that gets renewed on expiry.