关闭

[置顶] Android与服务器通信简单示例

130人阅读 评论(0) 收藏 举报
分类:

1.服务端(php)

<?php 
$ret = array('result'=>'Hello Wolrd');
echo json_encode($ret);
?>

2.客户端(android)

public class MainActivity extends Activity {
	private Button btn;
	private Handler handler;
	private String src;
 
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);//activity_main.xml文件省略
		btn=(Button) findViewById(R.id.button);
		btn.setOnClickListener(new OnClickListener() {
 
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
 
				new Thread(new Runnable() {
 
					@Override
					public void run() {
						// TODO Auto-generated method stub
						src=con();
						Message m=handler.obtainMessage();
						handler.sendMessage(m);
					}
				}).start();
			}
		});
		handler=new Handler()
		{
			public void handleMessage(Message msg) {
				try {
					JSONObject jsonObject = new JSONObject(src);
					String content=jsonObject.getString("result");
					btn.setText(content);		
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		};
 
	}
 
	public String con()
	{
		src=null;
		try {
			String str ="hello";
			URLConnection urlconn = new URL("http://10.0.0.99/t.php" ).openConnection();
			BufferedReader reader = new BufferedReader(new InputStreamReader(urlconn.getInputStream(), "utf-8"));
			String line = null;
			src="";
			while ((line = reader.readLine()) != null) {
				src += line;
			}
			System.err.println(src);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return src;
	}
}
3.在AndroidManifest.xml中添加访问网络权限 ,进行如下配置:
<uses-permission android:name="android.permission.INTERNET" />
4.结果显示

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:12825次
    • 积分:432
    • 等级:
    • 排名:千里之外
    • 原创:29篇
    • 转载:12篇
    • 译文:0篇
    • 评论:6条
    最新评论