网址在浏览器上工作正常,但在Android

时间:2017-02-08 20:10:58

标签: android json android-asynctask httpurlconnection

当我在浏览器上测试我的URL时,它会从服务器返回JSON数据。但是当我从AsyncTask调用它时,它在Android上返回null。我在Google上寻找答案,但我找不到任何东西。有人可以帮帮我吗?

 public List<User> getUsers() {
    List<User> users = new ArrayList<>();

    try {
        final String OUTPUT = "Output";
        URL url = new URL("MyUrl");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Accept", "application/json");

        if (conn.getResponseCode() != 200) {
            throw new RuntimeException("Failed : HTTP error code : "
                    + conn.getResponseCode());
        }

        BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
        System.out.println("Output from Server .... \n");
        StringBuilder sb = new StringBuilder();
        while ((br.readLine()) != null) {
            sb.append(br.readLine());
        }
        String output = sb.toString();
        ObjectMapper mapper = new ObjectMapper();
        //users = mapper.readValue(output, mapper.getTypeFactory().constructCollectionType(List.class, User.class));
        conn.disconnect();
        Log.d(OUTPUT,output);//I get null here
        return users;

    } catch (MalformedURLException e) {

    e.printStackTrace();

} catch (IOException e) {
    e.printStackTrace();
}
    return null;
}

这是我的AsyncTask:

public class GetUsersTask extends AsyncTask<Void,Void,List> {
    @Override
    protected List doInBackground(Void... voids) {
        UserClient client = new UserClient();
        List users = client.getUsers();
        return users;
    }
}

这就是我所说的:

usersTask = new GetUsersTask();
usersTask.execute();

提前致谢。

0 个答案:

没有答案