Nate
Nate

Reputation: 412

Two different JSON objects being returned from same URL?

I'm currently trying to send an URL to a server via my Android application, and I can send it fine, but it is returning a different JSON object (an access denied object), than if I send the same URL from my web browser. What could be causing this?

I have verified the URLs being sent are the same by outputting the URL I send in my app using Log.i and directly copy/pasting that into Chrome on my laptop.

The Two JSON Objects

// 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

Relevant Code:

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 Code

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;

    }

Upvotes: 0

Views: 469

Answers (1)

Dan Harms
Dan Harms

Reputation: 4840

I figured it would be good to add a solution in case anyone looks here. Your code was using HttpPost to create your network call. However, your URL was expecting a GET, so you needed to change to HttpGet. For future reference, if you have any parameters in your url (ie. anything after a "?"), it is usually expecting a GET call.

Happy coding!

Upvotes: 1

Related Questions