1

我正在尝试将一些数据从我的 android 代码发送到 php 文件。

并试图从 php 中取回它并在我的 java 代码的模拟器中显示它

`

       try{

      URL url = null;
      String s="http://10.0.2.2/welcome.php";
     url = new URL(s);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new   HttpPost(s);    
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                                                                                           HttpResponse response = httpclient.execute(httppost);

        Log.i("postData", response.getStatusLine().toString());
            reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
              stringBuilder = new StringBuilder();

              String line = null;
              while ((line = reader.readLine()) != null)
              {
                stringBuilder.append(line + "\n");
              }
        }

        catch(Exception e)
        {
            Log.e("log_tag", "Error in http connection "+e.toString());
        }  


        finally
        {
             tx.setText(stringBuilder.toString());
          // close the reader; this can throw an exception too, so
          // wrap it in another try/catch block.
          if (reader != null)
          {
            try
            {
              reader.close(); 
            }
            catch (IOException ioe)
            {  tx.setText((CharSequence) ioe);
              ioe.printStackTrace();
            }
          }
        }``

我通过打开两个不同的连接来做一个愚蠢的事情,一个用于发布,另一个用于获取,但问题不在于那个。它与我的 http-post.execute 方法。

我的 php 代码是 <?php $pLat = $_POST['pLat']; $pLng = $_POST['pLng']; print_r("$_POST['pLat']"); print_r("$_POST['pLng']"); ?>

我想我在发送我的数据时遇到了问题,因为如果我在我的 php 上回显 sumthing 它会显示在我的模拟器上。

请帮忙

4

1 回答 1

1

我真的建议您使用库来执行 HTTP 请求。事情变得容易多了。以Android Asynchronous Http Client为例。POST 数据和处理响应的示例:

AsyncHttpClient client = new AsyncHttpClient();
RequestParams rp = new RequestParams();
rp.put("pLat", "some value");
rp.put("pLong", "some other value");
client.post("http://10.0.2.2/welcome.php", rp, new AsyncHttpResponseHandler() {
    @Override
    public final void onSuccess(String response) {
        // handle your response here
    }

    @Override
    public void onFailure(Throwable e, String response) {
        // something went wrong
    }               
});
于 2013-04-26T08:08:04.030 回答