【问题标题】:Unable to make secure HTTPS POST request to REST API from Android无法从 Android 向 REST API 发出安全的 HTTPS POST 请求
【发布时间】:2013-11-30 19:59:52
【问题描述】:

我正在尝试对 RESTful API (last.fm) 进行 HTTPS POST;但是,REST 响应似乎表明我没有使用 HTTPS 进行连接。我的代码看起来像这样(为简洁起见,我只保留了最相关的部分)。我的代码有什么问题?

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);
}

【问题讨论】:

    标签: android rest post https last.fm


    【解决方案1】:

    我发现了我的问题(这很简单)。我在 URL 中使用 http 而不是 https。所以下面这行应该是

    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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-28
      • 1970-01-01
      • 2020-02-25
      相关资源
      最近更新 更多