Android HttpGet不起作用

时间:2015-01-26 17:32:46

标签: java android http-get

我遇到了HttpGet我在stackoverflow和其他网站上搜索过的问题,我甚至按照了一些例子但没有做任何事情,但它没有用。

这是我的代码:

    HttpClient          client = new DefaultHttpClient();
    HttpGet             request = new HttpGet("http://myurl.com/getit?token=" + _token);
    HttpResponse        response;
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    String              jsonString;
    Gson                gson;
    Modules[]           modulesList;

    try {
        response = client.execute(request);
        //jsonString = EntityUtils.toString(response.getEntity());
        //gson = new GsonBuilder().setPrettyPrinting().create();
        //modulesList = gson.fromJson(jsonString, Modules[].class);
    } catch (Exception e) {
        System.out.println("FAIL: " + e.getMessage());
    }

它总是返回空指针异常。 我尝试在Chrome中显示网址,复制/粘贴,网站会显示我的JSON。

2 个答案:

答案 0 :(得分:2)

问题在stacktrace的第一行非常清楚

/com.epitech.ferrei_j.epiandroid W / System.err:android.os.NetworkOnMainThreadException 01-26

Post 2.3 Android不允许您使用主UI线程执行可能需要一段时间才能完成的任务。网络IO就是其中之一。

您需要使用AsyncTask在自己的线程上执行操作。

有关如何执行此操作的示例,请参阅AsyncTask

答案 1 :(得分:0)

我经常写这样的:

  private String downloadUrl(String myurl) throws IOException {
        InputStream is = null;
        // Only display the first 500 characters of the retrieved
        // web page content.
        int len = 500;

        try {
            URL url = new URL(myurl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(READTIMEOUT /* milliseconds */);
            conn.setConnectTimeout(CONNECTTIMEOUT /* milliseconds */);
            conn.setRequestMethod("GET");
            conn.setDoInput(true);
            // Starts the query
            conn.connect();
            int response = conn.getResponseCode();
            //check to read content body if 400 error and above occurs.
            if (response >= HttpStatus.SC_BAD_REQUEST)
                is = conn.getErrorStream();
            else
                is = conn.getInputStream();

            // Convert the InputStream into a string
            String contentAsString = readIt(is, len);
            return contentAsString;

            // Makes sure that the InputStream is closed after the app is
            // finished using it.
        } finally {
            if (is != null) {
                is.close();
            }
        }
    }

    public String readIt(InputStream stream, int len) throws IOException,
            UnsupportedEncodingException {
        // Reader reader = null;
        // reader = new InputStreamReader(stream, "UTF-8");
        // char[] buffer = new char[stream.available()];
        // reader.read(buffer);
        // return new String(buffer);

        final BufferedReader r = new BufferedReader(new InputStreamReader(
                stream));
        final StringBuilder total = new StringBuilder();
        String line;
        while ((line = r.readLine()) != null) {
            total.append(line);
        }

        return total.toString();
    }

所以你事后要做的就是:

jsonString = downloadUrl( "http://myurl.com/getit?token=" + _token );