2015-05-18 56 views
0

我已经查看了所有过去的堆栈溢出问题,而我似乎无法弄清楚这一点。Android:从URI获取JSON

我想要做的是给一个uri并从中接收一个JSON。这是我到目前为止的代码:

public void setUpTheJSONs() throws IOException, JSONException, URISyntaxException { 
    jsonSummonerInfo = getJsonSummonerInfo(); 
    jsonSummonerRankedStats = getJsonRankedStats(); 
} 

public JSONObject getJsonSummonerInfo() throws IOException, JSONException, URISyntaxException { 
    HttpClient httpClient = new DefaultHttpClient(); 
    HttpPost httpPost = new HttpPost("https://na.api.pvp.net/api/lol/na/v1.4/summoner/by-name/kinoscorpia?api_key=my_api_key_here"); 
    HttpResponse response = httpClient.execute(httpPost); 
    HttpEntity entity = response.getEntity(); 

    if(entity != null){ 
     JSONObject temp = new JSONObject(EntityUtils.toString(entity)); 
     return temp; 
    } else { 
     return null; 
    } 

} 

} 

但是,我从来没有得到回应和响应= httpClient.execute(httpPost)线。

当您在网站中键入uri时,弹出JSON,但不会在代码运行时弹出。

任何帮助?

感谢☺

+0

哪里是你的'getJsonSummonerInfo()'方法执行?如果它在Activity或者Service中,你可能会得到一个NetworkOnMainThreadException异常。检查logcat是否有例外。 – Squonk

+0

你的清单中是否有INTERNET权限? – josephus

+0

我建议你不要发布你的api_key –

回答

0

随着DroidParts

public JSONObject getJsonSummonerInfo(Context ctx) throws HTTPException { 
    return new RESTClient2(ctx).getJSONObject("https://na.api.pvp.net/api/lol/na/v1.3/stats/by-summoner/30170613/ranked?season=SEASON2015&api_key=(**MYAPIKEY**)"); 
} 
+0

我不认为OP是在寻求替代方式做事 - 我想他可能想知道为什么他现有的代码不起作用 – Squonk

0

代码本身没有问题。
也许链接被打破。
检查链接抛出HTTP错误或由该URI
https://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=stackoverflow

+0

我更新了代码。我只是没有从它得到一个JSON。但是,当我将uri放入网页时,JSON弹出。我究竟做错了什么? –

+0

将'entity'和'response'打印到控制台并检查它,httpget可能是问题 – YukiNyaa

2

检查代码是否确定你的意思做一个POST请求?你的代码似乎实际上并没有发送任何东西到服务器,而在POST请求中你通常会附加一些东西给请求实体。

尝试发送它作为一个GET请求,看看是否能解决你的问题:

public JSONObject getJsonSummonerInfo() throws IOException, JSONException, URISyntaxException 
{ 
    HttpClient httpClient = new DefaultHttpClient(); 
    HttpGet httpGet = new HttpGet("https://na.api.pvp.net/api/lol/na/v1.4/summoner/by-name/kinoscorpia?api_key=my_api_key_here"); 

    HttpResponse response = httpClient.execute(httpGet); 
    HttpEntity entity = response.getEntity(); 

    if(entity != null) 
    { 
     JSONObject temp = new JSONObject(EntityUtils.toString(entity)); 
     return temp; 
    } 
    else 
    { 
     return null; 
    } 
} 
+0

同意,您需要使用HttpGet,此API的所有服务均为GET –

+1

获胜者!就是这样,我只是对它进行了测试。只要他不试图在主UI线程上运行它,它就会为他工作。顺便说一句,我编辑你的文章的唯一原因是删除他的API密钥。 –