2017-01-10 47 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();