getOutputStream之后代码将无法执行 - Android

时间:2017-01-10 15:05:01

标签: java android

我正在尝试使用POST命令从Web服务获取一些数据。但我坚持这个奇怪的事情:我的代码在某一点之后没有执行,我真的不知道为什么。我使用了断点和Log.d()来检查它。

private void getResponse(String code)
    {
        String strurl = "http://example.com/api/something.json";
        String Token = app.Settings.UserToken;
        String myid= app.ID.toString();



        try {
            URL url = new URL(strurl);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

            urlConnection.setDoOutput(true);
            urlConnection.setConnectTimeout(5000); 
            urlConnection.setRequestMethod("POST");
            urlConnection.setRequestProperty("Content-Type", "text/plain");
            OutputStream out = urlConnection.getOutputStream();

            String outstr = "{\"response\": {";
            outstr += "\"token\":\"" + Token + "\",";
            outstr += "\"myid\":\"" + myid+ "\",";
            outstr += "\"code\":\"" + code + "\",";
            outstr += "}}";

            out.write(outstr.getBytes());

            int respCode = urlConnection.getResponseCode();

            if (respCode == 200) {

                Gson gson = new GsonBuilder()
                        .registerTypeAdapter(Boolean.class, new BooleanTypeAdapter())
                        .create();

                InputStream in = urlConnection.getInputStream();
                JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8"));


                reader.beginObject();
                while (reader.hasNext()) {
                    String token = reader.nextName();

                    if (token.equals("name")) {

                    }

                }
                reader.endObject();

                reader.close();
            } else {
                return;
            }
            urlConnection.disconnect();


            return;

        } catch (Exception e) {
            e.printStackTrace();
            return;
        } finally {

        }
    }

此行之后

OutputStream out = urlConnection.getOutputStream();

什么都没有被执行。知道为什么吗?

2 个答案:

答案 0 :(得分:0)

写入后用于将消息发送到文件描述符的简单刷新。

out.flush();

答案 1 :(得分:0)

我发现了问题所在。我得到了一个networkonmainthreadexception,因为我没有在AsyncTask中运行该函数。