2013-01-04 65 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权限。