API连接仅运行一次

时间:2016-03-18 17:26:55

标签: java api

我正在创建一个调用Hitbox API的应用程序。我正在尝试获取游戏名称(从列表中列为category_name。

到目前为止,我已经设法在程序运行阶段获得游戏名称一次,但是当我改变从哪里获取游戏名称时,程序没有做任何事情。我不知道是什么原因导致它不向服务器发送另一个请求。

public void apiConnect(){
    String channel = text.getText();
    HttpClient client = new DefaultHttpClient();
    HttpGet request = new HttpGet("http://api.hitbox.tv/media/live/" + channel);
    HttpResponse response = null;
    try {
        response = client.execute(request);
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    // Get the response
    BufferedReader rd = null;
    try {
        rd = new BufferedReader
          (new InputStreamReader(response.getEntity().getContent()));
    } catch (UnsupportedOperationException | IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    String line = "";
    try {
        while ((line = rd.readLine()) != null) {
          hitbox.append(line);
        }
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } 
    try {
        FileUtils.writeStringToFile(new File("hitbox.json"), hitbox.getText());
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    String game = null;
    FileInputStream fileHitbox = null;
    try {
        fileHitbox = new FileInputStream(new File("hitbox.json"));
    } catch (FileNotFoundException e2) {
        // TODO Auto-generated catch block
        e2.printStackTrace();
    }

    String strHitbox = null;
    try {
        strHitbox = IOUtils.toString(fileHitbox, "UTF-8");
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    JSONObject obj = new JSONObject(strHitbox);
    JSONArray ar = obj.getJSONArray("livestream");
    for (int i = 0; i < ar.length(); i++)
    {
        game = ar.getJSONObject(i).getString("category_name");
        nameOf.setText("Game Name: " + game);
    }
    File hb = new File("hitbox.json");
    if(hb.exists()){
        hb.delete();
    }
}

以上示例是已定义的函数,Get Game Name按钮代码如下:

btnGetGameName.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            apiConnect();

    }
    });

有人可以建议在第一次请求后导致它无效的原因,并且如果可能的话建议解决方案吗?

编辑:我发现了这个问题。从API读取数据将附加到hitbox变量。因此我添加了一个片段来清除&#34; hitbox&#34;按下按钮时变量有效,这意味着代码可以正常工作。

1 个答案:

答案 0 :(得分:0)

尝试在阅读后使用您的回复以释放资源:

rd = new BufferedReader
      (new InputStreamReader(response.getEntity().getContent()));        
response.getEntity().consumeContent();
//Or if you have EntityUtils
EntityUtils.consume(response.getEntity());

source