Question

I'm trying to make an HTTPS POST to a RESTful API (last.fm); however, the REST response seems to indicate that I'm not connecting in HTTPS. My code looks like this (I've kept only the most relevant parts for sake of brevity). What is wrong with my code?

public String getSessionKey(String username, String pass) throws 
         NoSuchAlgorithmException, ClientProtocolException, IOException {

    HttpClient hc = createHttpClient();

    // Construct API signature string 
    String api_sig = "<constructed api sig goes here>"

    // compute md5 hash of API signature string using md5 method    
    String api_sig_md5 = md5(api_sig); 


    HttpPost hp_auth = new HttpPost("http://ws.audioscrobbler.com/2.0/"
                + "?method=auth.getMobileSession" 
                + "&username=" + username 
                + "&password=" + pass 
                + "&api_key=" + getString(R.string.lastfm_key)
                + "&api_sig=" + api_sig_md5);

    HttpResponse resp = hc.execute(hp_auth);

    // code to convert/parse "resp" XML response to retrieve the session key

    return key; // return session key
}

private HttpClient createHttpClient()
{
    HttpParams params = new BasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, HTTP.DEFAULT_CONTENT_CHARSET);
    HttpProtocolParams.setUseExpectContinue(params, true);

    SchemeRegistry schReg = new SchemeRegistry();
    schReg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    schReg.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
    ClientConnectionManager conMgr = new ThreadSafeClientConnManager(params, schReg);

    return new DefaultHttpClient(conMgr, params);
}
Was it helpful?

Solution

I figured out my issue (which is pretty trivial). I was using http in the URL rather than https. So the following line should be

HttpPost hp_auth = new HttpPost("https://ws.audioscrobbler.com/2.0/"
                + "?method=auth.getMobileSession" 
                + "&username=" + username 
                + "&password=" + pass 
                + "&api_key=" + getString(R.string.lastfm_key)
                + "&api_sig=" + api_sig_md5);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top