Android与PHP交谈

时间:2014-08-16 19:07:49

标签: php android

我是Android新手,目前正在尝试通过PHP将Android连接到数据库。我可以轻松地将PHP脚本连接到我的数据库,但我无法让Android与PHP脚本通信。我尝试过多个例子 - http://www.androidaspect.com/2013/05/how-to-connect-android-with-php.html - 但似乎无法让它发挥作用。如果我能让Android从PHP脚本中收到一条说“你好”的消息,我很容易就能完成我的工作,但我不能。我被告知要做一些事情,比如使用ASync,但坦率地说,这让事情变得更加复杂。在让我的Android方面与我的PHP方面交谈时,任何帮助都会受到赞赏。非常感谢你提前。

我已经删除了我尝试过的实际代码,但上面链接了一个教程,另一个让我试试这个 -

ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("rec","mar"));
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2/select.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost); 
HttpEntity entity = response.getEntity();
is = entity.getContent();
BufferedReader reader = new BufferedReader
            (new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
{
   sb.append(line + "\n");
}
is.close();
result = sb.toString();
JSONObject json_data = new JSONObject(result);
name=(json_data.getString("name"));
Toast.makeText(getBaseContext(), "Name : "+name,
        Toast.LENGTH_SHORT).show();

2 个答案:

答案 0 :(得分:2)

使用以下类作为内部类并更改网址和参数:

class PlaceOrder extends AsyncTask<Void, Void, Void> {

        @Override
        protected Void doInBackground(Void... params) {

            // TODO Auto-generated method stub

            try {

                HttpClient httpClient = new DefaultHttpClient();

                HttpPost httpPst = new HttpPost(

                "yout_url");

                ArrayList<NameValuePair> parameters = new ArrayList<NameValuePair>(

                2);

                parameters.add(new BasicNameValuePair("username", "apple"));

                parameters.add(new BasicNameValuePair("pw", "apple"));

                parameters.add(new BasicNameValuePair("email",
                        "apple@gmail.com"));

                parameters.add(new BasicNameValuePair("name", "apple"));

                httpPst.setEntity(new UrlEncodedFormEntity(parameters));

                HttpResponse httpRes = httpClient.execute(httpPst);

                String str = convertStreamToString(
                        httpRes.getEntity().getContent()).toString();

                Log.i("mlog", "outfromurl" + str);

            } catch (UnsupportedEncodingException e) {

                // TODO Auto-generated catch block

                e.printStackTrace();

            } catch (ClientProtocolException e) {

                // TODO Auto-generated catch block

                e.printStackTrace();

            } catch (IOException e) {

                // TODO Auto-generated catch block

                e.printStackTrace();

            }

            return null;

        }

    }

    public static String convertStreamToString(InputStream is) {

        BufferedReader reader = new BufferedReader(new InputStreamReader(is));

        StringBuilder sb = new StringBuilder();

        String line = null;

        try {

            while ((line = reader.readLine()) != null) {

                sb.append(line + "\n");

            }

        } catch (Exception e) {

            e.printStackTrace();

        } finally {

            try {

                is.close();

            } catch (IOException e) {

                e.printStackTrace();

            }

        }

        return sb.toString();

    }

使用http://json.parser.online.fr/验证json

答案 1 :(得分:0)

我可以建议你使用RETROFIT:

http://square.github.io/retrofit/

简单介绍一下。

针对Android进行了优化,以便在MainThread上执行Response Callbacks,以便您可以操作UI控件。

示例:

public interface TimetrackingService {

    @GET("/projekte")
    void getProjects(Callback<List<Project>> cb);

    @POST("/timetrack")
    void submit(
            @Query("projektId") int projektId, 
            @Query("start") String start, 
            @Query("ende") String ende, 
            Callback<Void> cb);
}
public class Project {

    public int id;
    public String name;

}
RestAdapter restAdapter = new RestAdapter.Builder()
    .setEndpoint(url)
    .build();
TimetrackingService service = restAdapter.create(TimetrackingService.class);


    service.getProjects(new Callback<List<Project>>() {

        @Override
        public void success(List<Project> list, Response response) {
            Log.d(LOG, "success");
        }

        @Override
        public void failure(RetrofitError e) {
            Log.d(LOG, "failure");
        }

    });