Android 中参数未传递到 URL

问题描述 投票:0回答:1

好吧,我已经查看了多个示例,我的代码似乎是正确的,但出于某种原因,参数没有添加到 URL 中。我正在尝试连接到 Last.Fm API,我的代码如下:

searchIT.setOnClickListener(new OnClickListener() 
    {
        
        @Override
        public void onClick(View v) 
        {
            // TODO Auto-generated method stub
            //Create new HTTPClient and Post header
            HttpPost API_ROOT = new HttpPost("http://ws.audioscrobbler.com/2.0/");
            HttpClient httpclient = new DefaultHttpClient();
            
            try 
            {
                //Add Data
                List<NameValuePair> nameValPairs = new ArrayList<NameValuePair>(4);
                
                nameValPairs.add(new BasicNameValuePair("method", "artist.getevents")); //Get events for artist
                nameValPairs.add(new BasicNameValuePair("artist", namesBox.getText().toString()));  //Get artist name
                nameValPairs.add(new BasicNameValuePair("autocorrect", "1"));   //Turn on AutoCorrect
                nameValPairs.add(new BasicNameValuePair("api_key", "xxxxxxxxxxxxxxxxxxxx")); //API Key - redacted for privacy
                API_ROOT.setEntity(new UrlEncodedFormEntity(nameValPairs));
                Log.i(TAG, "URL: " + API_ROOT.getURI().toString());
                
                //Execute HTTP Post Request
                HttpResponse response = httpclient.execute(API_ROOT);
                
                
            } 
            catch (UnsupportedEncodingException e) 
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } 
            catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } 
            catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    });

我在这里错过了什么吗?在日志中,网址显示为:http://ws.audioscrobbler.com/2.0/,因此它似乎缺少我试图传递给它的所有参数。有什么想法、提示、更正或建议吗?

android last.fm
1个回答
0
投票

从 onClick 方法启动一个新活动并传递您想要的所有参数

            HashMap<String, String> o = (HashMap<String, String>) searchList.getItemAtPosition(position);
            Intent i = new Intent(SearchActivity.this, SearchDetails.class);
            i.putExtra("method", o.get("method"));
            i.putExtra("artist", o.get("artist"));
            i.putExtra("autocorrect", o.get("autocorrect"));
            i.putExtra("api_key", o.get("api_key"));

然后在您的新活动中:在 onCreate 方法中

    Intent myIntent = getIntent(); 
    String method= myIntent.getStringExtra("method");
    String artist= myIntent.getStringExtra("artist");
    String autocorrect= myIntent.getStringExtra("autocorrect");
    String api_key= myIntent.getStringExtra("api_key");

现在您将根据需要获取参数并将它们添加到您的 URL 中。

希望有效果

© www.soinside.com 2019 - 2024. All rights reserved.