参数未在Android中传递到URL

时间:2011-06-08 04:39:34

标签: android api httpclient last.fm

好的,我查看过多个示例,我的代码似乎是正确的,但是出于什么原因,参数没有添加到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/,因此它似乎缺少我尝试传递给它的所有参数。任何想法,提示,更正或建议?谢谢!

1 个答案:

答案 0 :(得分: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");

现在,您可以根据需要获取参数并将其添加到您的网址中。

希望它有效