2013-01-04 64 views
1

我正在處理2個需要發送到php文件相同字符串的相同應用程序。 iOs之一是一個GET,當我在PHP中使用這個代碼來檢查它。Android從(HTTP)POST到GET

file_put_contents('dump.txt', "POST: \n" . print_r($_POST, true) . "\n\n\n GET: \n" . print_r($_GET, true)); 

但Android的一個是職位,但他們需要exactely一樣的,因爲我已經把PHP的工作一部分,我不能再更改。

這裏是我的Android代碼:

HttpClient httpclient = new DefaultHttpClient(); 
      HttpPost httpost = new HttpPost("http://Myserver.com/default.php"); 

      json = new JSONObject(); 
      try { 
       json.put("id", "69403"); 
       json.put("longitude", longi); 
       json.put("latitude", lat); 
       json.put("timestamp", time); 

      } catch (JSONException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
      } 

      /// create StringEntity with current json obejct 

      try { 
      // StringEntity se = new StringEntity(json.toString()); 

       List <NameValuePair> nvps = new ArrayList <NameValuePair>(); 
       nvps.add(new BasicNameValuePair("data", json.toString())); 
       httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8)); 


       System.out.println("send about to do post"); 
       try { 
        response = httpclient.execute(httpost); 
       } catch (ClientProtocolException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
       } catch (IOException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
       } 
       System.out.println("send post done"); 
       HttpEntity entity = response.getEntity(); 


      } catch (UnsupportedEncodingException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
      } 
+1

那麼你爲什麼不嘗試HttpGet在Android? – user370305

+0

剛剛改變了嗎?因爲我已經嘗試過,但它墜毀 –

+0

看看http://w3mentor.com/learn/java/android-development/android-http-services/example-of-http-get-request-using-httpclient-in-android /和http://www.softwarepassion.com/android-series-get-post-and-multipart-post-requests/用於HttpGet。如果它崩潰,那麼你必須發生崩潰.. – user370305

回答

0

變化:

HttpPost httpost = new HttpPost("http://Myserver.com/default.php"); 

HttpGet httpget = new HttpGet("http://Myserver.com/default.php"); 
+0

當我改變這個我得到這個錯誤:\t \t httpost.setEntity(new UrlEncodedFormEntity(nvps,HTTP.UTF_8)); ((HttpResponse)httpost).setEntity(new UrlEncodedFormEntity(nvps,HTTP.UTF_8));並且它想將其更改爲\t \t((HttpResponse) 但它然後崩潰 –

+0

你能更清楚,因爲你看到的錯誤信息是什麼? –

+0

setEntity錯誤。可能的解決方案:將其添加到httppost。然後它會((HttpResponse)httpost).setEntity(new UrlEncodedFormEntity(nvps,HTTP.UTF_8)); –

0

如果你得到NetworkOnMainThreadException,那是因爲你正在試圖做的網絡操作來自主線程。如果是這樣,請嘗試查看AsyncTask

此外,請確保您獲得了Android清單中的Internet權限。