<pre name="code" class="java">MainActivity.java
public class MainActivity extends Activity {
private Context context;
private TextView test;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
test = (TextView) this.findViewById(R.id.test);
JsonUtils.HttpClientGet("http://www.baidu.com/", "UTF-8", new MyCallBack() {
@Override
public void getStringResult(final String result) {
test.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(context, result, 0).show();
}
});
}
});
}
}
<pre name="code" class="java">JsonUtils.java
<pre name="code" class="java">public class JsonUtils {
public static void HttpClientGet(final String strurl, final String charset, final MyCallBack myCallBack) {// 1.0HttpClient
new Thread() {
public void run() {
HttpResponse response = null;
try {
HttpClient httpClient = new DefaultHttpClient(); // 1.0HttpClient对象
HttpGet request = new HttpGet(strurl); // 1.1HttpGet对象
response = httpClient.execute(request);//
// 1.2获得HttpResponse对象
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {// 1.3请求200
String result = EntityUtils.toString(response.getEntity(), charset);// 1.4响应成字符串,设置编码
myCallBack.getStringResult(result);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
};
}.start();
}
// 回调函数
public interface MyCallBack {
public void getStringResult(String result);
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<TextView
android:id="@+id/test"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="获取网络Json" />
</RelativeLayout>