2016-10-08 47 views
1

我正在嘗試發佈評論到網站,POST似乎沒有給出錯誤,但似乎也沒有工作。我不確定我哪裏出錯了?我稱它在一個單獨的線程Android POST發表評論到一個網站

Thread thread = new Thread(new Runnable() { 
     @Override 
     public void run() { 
      HttpURLConnection conn = null; 
      try { 
       String urlString = mainUrl +"?name=" + name; 
       URL url = new URL(urlString); 

       conn = (HttpURLConnection) url.openConnection(); 
       conn.setRequestMethod("POST"); 
       conn.setDoOutput(true); 
       conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
       conn.getOutputStream().write(comment.getBytes("UTF8")); 
       conn.connect(); 

       int responseCode = conn.getResponseCode(); 
       Log.d("Response Code: ", "" + responseCode); 


      } catch (Exception e) { 
       Log.e("POST ERROR", e.toString()); 
      } 
      finally { 
       if (conn != null) { 
        conn.disconnect(); 
       } 
      } 
     } 
    }); 
    thread.start(); 
+0

刷新輸出流緩衝區 – xFighter

回答

0

試試這個:

try { 
      String urlString = mainUrl +"?name=" + name; 
      url = new URL(urlString); 
      urlConnection =(HttpURLConnection) url.openConnection(); 
      urlConnection.setRequestProperty("Content-Type", "application/json"); 
      urlConnection.setRequestMethod("POST"); 
      urlConnection.setDoInput(true); 
      urlConnection.setDoOutput(true); 
      urlConnection.connect(); 
      setupDataToDB(); 
      outputStreamWriter = new OutputStreamWriter(urlConnection.getOutputStream()); 
      outputStreamWriter.write(dataToWrite.toString()); 
      Log.e("Data To Write", dataToWrite.toString()); 

      outputStreamWriter.flush(); 
      outputStreamWriter.close(); 
      int responseCode = urlConnection.getResponseCode(); 
      Log.e("Response Code ", String.valueOf(responseCode)); 
      if (responseCode == 404){ 
       Log.e("Status Code", "404"); 
      }else if (responseCode == 200){ 
       Log.e("Status Code", "200"); 
     } catch (Exception e) { 
      urlConnection.getErrorStream(); 
      e.printStackTrace(); 
     } 

    private void setupDataToDB() { 
     dataToWrite = new JSONObject(); 
     try { 
      dataToWrite.put("comment", comment); 
     } catch (JSONException e) { 
      e.printStackTrace(); 
     } 
    } 

不要忘記宣佈這些爲全局變量:

private HttpURLConnection urlConnection; 
private URL url; 
private OutputStreamWriter outputStreamWriter; 
private JSONObject dataToWrite; 

希望它可以幫助!