您的位置:首页 > 移动开发 > Android开发

android链接服务端数据库

2016-07-28 14:24 477 查看
<?php

header(\"Content-Type: text/html; charset=UTF-8\");

$array=array(\'title\'=>\'name\',\'value\'=>\'dog\');

echo json_encode($array);

?>

android 端的代码 如下:

package com.example.jsontest;

import java.io.BufferedReader;

import java.io.InputStreamReader;

import org.apache.http.HttpResponse;

import org.apache.http.client.HttpClient;

import org.apache.http.client.methods.HttpGet;

import org.apache.http.impl.client.DefaultHttpClient;

import org.json.JSONObject;

import android.os.Bundle;

import android.app.Activity;

import android.view.View;

import android.widget.Button;

import android.widget.EditText;

public class MainActivity extends Activity {

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        Button btn = (Button) findViewById(R.id.getPhpJson);

        btn.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {

                EditText edit = (EditText) findViewById(R.id.typeId);

                String url = \"http://192.168.191.1/test/json.php\";

                edit.setText(\"begin\");

                getServerJsonDataWithNoType(url, edit);

            }

        });

    }

    public void getServerJsonDataWithNoType(String url, EditText editText) {

        int res = 0;

        HttpClient client = new DefaultHttpClient();

        StringBuilder str = new StringBuilder();

        HttpGet httpGet = new HttpGet(url);

        try {

            HttpResponse httpRes = client.execute(httpGet);

            httpRes = client.execute(httpGet);

            res = httpRes.getStatusLine().getStatusCode();

            if (res == 200) {

                BufferedReader buffer = new BufferedReader(

                        new InputStreamReader(httpRes.getEntity().getContent()));

                for (String s = buffer.readLine(); s != null; s = buffer

                        .readLine()) {

                    str.append(s);

                }

                String newstr = new String(str.toString().getBytes(), \"UTF-8\");

                editText.setText(newstr);

                JSONObject json = new JSONObject(newstr);

                String title = json.getString(\"title\");

                String value = json.getString(\"value\");

                editText.setText(title + value);

            } else {

            }

        } catch (Exception e) {

            e.printStackTrace();

        }

    }

}

注意要把字符串转为utf8编码,因为String 默认是unicode编码的。

String newstr = new String(str.toString().getBytes(), \"UTF-8\");

再然后就是

别忘了在AndroidManifest.xml中给app加上权限:草坪销售

 <uses-permission android:name=\"android.permission.INTERNET\" />

这样这个例子就OK了

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  数据库 android