从同一个URL返回两个不同的JSON对象?

时间:2014-04-07 19:40:41

标签: android json

我正在尝试通过我的Android应用程序向服务器发送一个URL,我可以发送它,但它返回一个不同的JSON对象(一个访问被拒绝的对象),而不是从我发送相同的URL我的网络浏览器。可能导致这种情况的原因是什么?

我已经通过输出我在我的应用中使用Log.i发送的网址并将其直接复制/粘贴到我的笔记本电脑上的Chrome中来验证发送的网址是否相同。

两个JSON对象

// From app
{"status":{"status_code":401,"message":"Access denied"}}

// From web
{"nv43":{"id":23591778,"name":"NV43","profileIconId":22,"summonerLevel":30,"revisionDate":1396737099000}}

//URL being sent
https://prod.api.pvp.net/api/lol/na/v1.4/summoner/by-name/nv43?api_key=d96236d2-6ee3-4cfd-afa7-f41bdbc11128

相关守则:

package edu.appdesign.leaguestats;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

public class StatsActivity extends Activity {

    TextView textId;
    TextView textName;
    TextView textProfileIconId;
    TextView textRevisionDate;
    TextView textSummonerLevel;
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.stats_activity);

        final Button viewMasteries = (Button) findViewById(R.id.masteries);
        final Button viewRunes = (Button) findViewById(R.id.runes);

        viewRunes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent intent = new Intent(StatsActivity.this, RunesActivity.class);
                startActivity(intent);
            }
        });

        viewMasteries.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent intent = new Intent(StatsActivity.this, MasteriesActivity.class);
                startActivity(intent);
            }
        });

        GetStats stats = new GetStats();
        stats.execute();
    }

    class GetStats extends AsyncTask<String, String, JSONObject> {

        private String api_key="d96236d2-6ee3-4cfd-afa7-f41bdbc11128";
        String region = MainActivity.region.toLowerCase();
        String name = MainActivity.name;
        String url = null;
        String encodedName = null;
        String encodedKey = null;
        String encodedRegion = null;
        String status = "status";
        String LOG = "JSONFetched";

        // JSON Node Names
        String TAG_ID = "id";
        String TAG_NAME = "name";
        String TAG_PROFILEICONID = "profileIconId";
        String TAG_REVISIONDATE = "revisionDate";
        String TAG_SUMMONERLEVEL = "summonerLevel";

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            try {
                textId = (TextView) findViewById(R.id.id);
                textName = (TextView) findViewById(R.id.name);
                textProfileIconId = (TextView) findViewById(R.id.profileIconId);
                textRevisionDate = (TextView) findViewById(R.id.revisionDate);
                textSummonerLevel = (TextView) findViewById(R.id.summonerLevel);
                encodedName = URLEncoder.encode(name, "UTF-8");
                encodedKey = URLEncoder.encode(api_key, "UTF-8");
                encodedRegion = URLEncoder.encode(region, "UTF-8");
                url = "https://prod.api.pvp.net/api/lol/" + encodedRegion + "/v1.4/summoner/by-name/" + encodedName + "?api_key=" + encodedKey;
                Log.i("..........", url);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

        }

        @Override
        protected JSONObject doInBackground(String... arg0) {
            JSONParser jParser = new JSONParser();

            // Get JSON from URL
            JSONObject json = jParser.getJSONFromUrl(url);
            Log.i("............", "" + json);
            JSONObject jb = null;

            try {
                jb = json.getJSONObject(encodedName);

            } catch (JSONException e) {
                e.printStackTrace();
            };
            return jb;
        }

        @Override
        protected void onPostExecute(JSONObject json) {
            try {
                // Storing JSON item to String
                String id = json.getString(TAG_ID);
                String name = json.getString(TAG_NAME);
                String icon = json.getString(TAG_PROFILEICONID);
                String revDate = json.getString(TAG_REVISIONDATE);
                String sumLevel = json.getString(TAG_SUMMONERLEVEL);

                // Putting JSON data in TextViews
                String tmp = String.valueOf(id);
                textId.setText(tmp);
                textName.setText(name);
                textProfileIconId.setText(icon);
                textRevisionDate.setText(revDate);
                textSummonerLevel.setText(sumLevel);

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }
}

getJSONFromUrl代码

public JSONObject getJSONFromUrl(String url) {

        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }

1 个答案:

答案 0 :(得分:1)

我认为添加解决方案会很好,以防有人看到这里。您的代码使用HttpPost来创建网络呼叫。但是,您的网址期望获得GET,因此您需要更改为HttpGet。为了将来参考,如果您的网址中有任何参数(例如,在&#34;?&#34;之后的任何内容),通常期待GET通话。

快乐的编码!