2017-01-10 24 views
-1

我想从POST命令中获取一些web服务的数据。但是我陷入了这个奇怪的事情:我的代码在某个点后不能执行,我真的不知道为什么。我使用断点和Log.d()来检查它。getOutputStream后不执行代码 - Android

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(); 

后没有得到执行。任何想法为什么?

回答

0

我发现问题出在哪里。我得到了networkonmainthreadexception,因为我没有在AsyncTask中运行函数。

0

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

out.flush();