现在android应用很多使用json通信,据说是这样。
就在网上找示例想来看看 但是没找到直接down下来就可以用的,找了一个比较靠谱的,略加修改。跑通了。
php端如下:
注意要把格式转换成utf-8,最保险就是将整个文件转化成utf8编码。
<?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" />