您的位置:首页 > 理论基础 > 计算机网络

Android基础学习之Socket、Http、Json网络编程

2015-10-17 23:50 816 查看
Android基础学习之Socket、Http、Json网络编程

android 网络编程api

1.java.net包

2.org.apache.http包

3.android.net包

4.用框架 volley

使用类型:

1.做基本socket通信

2.访问web资源

主要类:

java.net包

Socket/ServerSocket 通信

URL

URLConnection

HttpURLConnection

org.apache.http包

核心接口:HttpClient 实现http客户端,具有浏览器的基本功能,但不能对页面进行解析和显示。可实现http连接管理。

实现类:

AndroidHttpClient

DefaultHttpClient

重载大量的execute()

final HttpResponse execute(HttpUriRequest request) //request封装请求参数

//返回一个响应的对象

HttpUriRequest接口

URL请求方式:

1.get请求(默认):会在url后面附加参数,如 http://…./?username=rose&password=123&key=value

HttpGet 类

java.lang.Object
org.apache.http.message.AbstractHttpMessage
org.apache.http.client.methods.HttpRequestBase
org.apache.http.client.methods.HttpGet


2.post请求:不会url后面附加参数,打包请求参数,不能看到打包数据 更安全

HttpPost 类

java.lang.Object
org.apache.http.message.AbstractHttpMessage
org.apache.http.client.methods.HttpRequestBase
org.apache.http.client.methods.HttpEntityEnclosingRequestBase
org.apache.http.client.methods.HttpPost


HttpEntity 接口用来封装post请求参数的对象

实现类:UrlEncodedFormEntity

UrlEncodedFormEntity(List< ? extends NameValuePair> parameters, String encoding)


NameValuePair接口
BasicNameValuePair实现类


使用流程:

1.创建httpclient对象

2.设置参数和请求属性

3.获得httpresponse对象进行操作

注意:

1.添加网络访问权限

2.Caused by: android.os.NetworkOnMainThreadException 错误

从Honeycomb SDK(3.0)开始,google不再允许网络请求(HTTP、Socket)等相关操作直接

在Main Thread类中,其实本来就不应该这样做,直接在UI线程进行网络操作,会阻塞UI。

所以,也就是说,在Honeycomb SDK(3.0)以下的版本,你还可以继续在Main Thread里这样做,在3.0以上,就不行了,建议使用异步操作方式:

Handler handler=new Handler(){
handleMessage(){
//更新UI代码
}
};

onCreate(){

new Thread(){
run(){
connection();
//更新UI
handler.sendMessage(msg;
}
}

connection(){
//网络请求可能阻塞的情况
}
}


1.Socket部分

更多socket例子请移步:JAVA基础学习之TCP网络编程

示例:

活动客户端:

public class MainActivity extends Activity {
protected static final int CONNECTOK = 0;
protected static final int CONNECTFAIL = 1;
protected static final int READOK = 2;
protected static final int READFAIL = 3;
Button btn;
EditText edit;
TextView txt;
InputStream is=null;
OutputStream os=null;
DataInputStream dis=null;
DataOutputStream dos=null;
Socket socket;
Handler hanlder=new Handler(){
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case CONNECTOK:
Toast.makeText(MainActivity.this, "服务器连接成功!", Toast.LENGTH_SHORT).show();
break;
case CONNECTFAIL:
Toast.makeText(MainActivity.this, "服务器连接失败!", Toast.LENGTH_SHORT).show();
break;
case READOK:
Toast.makeText(MainActivity.this, "读服务器成功!", Toast.LENGTH_SHORT).show();
break;

case READFAIL:
Toast.makeText(MainActivity.this, "读服务器失败!", Toast.LENGTH_SHORT).show();
break;
default:
break;
}
}
};

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edit=(EditText)findViewById(R.id.editText1);
btn=(Button)findViewById(R.id.button1);
txt=(TextView)findViewById(R.id.textView1);
connectServer();
btn.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
Login();
}
});
}

private void connectServer() {
final ProgressDialog dialog=new ProgressDialog(this);
dialog.setTitle("连接提示");
dialog.setMessage("正在连接服务器,请稍后...");
dialog.show();
new Thread(){
public void run() {
try {
socket=new Socket("192.168.7.5",2345);//阻塞点
is=socket.getInputStream();
os=socket.getOutputStream();
//连接到socket的输出流os,用DataOutputStream包装
dos=new DataOutputStream(os);
dis=new DataInputStream(is);

hanlder.sendEmptyMessage(CONNECTOK);

} catch (UnknownHostException e) {
e.printStackTrace();
hanlder.sendEmptyMessage(CONNECTFAIL);
} catch (IOException e) {
e.printStackTrace();
hanlder.sendEmptyMessage(CONNECTFAIL);
}
dialog.dismiss();
}
}.start();
}

protected void Login() {

new Thread(){
public void run() {
//将数据发送到server端
try {
dos.writeUTF(edit.getText().toString().trim());
dis=new DataInputStream(is);
String input=dis.readUTF();//阻塞点
txt.setText(input);
hanlder.sendEmptyMessage(READOK);
} catch (IOException e) {
e.printStackTrace();
hanlder.sendEmptyMessage(READFAIL);
}
}
}.start();
}

}


服务器端,java控制台程序:

public class Server {
public static void main(String[] args) {
ServerSocket srv=null;
Socket client=null;
InputStream is=null;
OutputStream os=null;
DataInputStream dis=null;
DataOutputStream dos=null;

try {
System.out.println("my server have started....");
srv=new ServerSocket(2345);
client=srv.accept();
is=client.getInputStream();
os=client.getOutputStream();

dis=new DataInputStream(is);
dos=new DataOutputStream(os);

//读客户端发送来的数据
String output=null;
String pwd=dis.readUTF();
if("123456".equals(pwd)){
output="welecome you!!!";
}else{
output="you can not visit my server!!!";
}
dos.writeUTF(output);

} catch (IOException e) {
e.printStackTrace();
}finally{
try {
dos.close();
dis.close();
is.close();
os.close();
client.close();
srv.close();
} catch (IOException e) {
e.printStackTrace();
}

System.out.println("my server have shutdown....");
}
}
}


2.Http部分

主要用于下载web网络资源或和网络服务器进行交互。

更多http例子请移步:JAVA基础学习之Http(含JSON)网络编程

URL类

URL url=new URL(“http://…..”);

InputStream is=url.openStream();

URLConnection con=openConnection(); //协议无关连接对象

HttpURLConnection con=openConnection();//http协议连接对象 请求/响应头信息

用法:

URL url = new URL("http://www.android.com/...");//URL对象和网络资源url
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();//打开连接
try {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());//得到资源
readStream(in);//读取资源的方法
finally {
urlConnection.disconnect();//关闭连接
}


示例1:

1.1使用线程和消息,访问网络,下载图片和音乐

1.xml布局

<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="62dp"
android:layout_marginTop="14dp"
android:text="下载图片" />

<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/button1"
android:layout_alignBottom="@+id/button1"
android:layout_marginLeft="16dp"
android:layout_toRightOf="@+id/button1"
android:text="下载MP3" />

<ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/button1"
android:layout_marginLeft="43dp"
android:layout_marginTop="38dp"
android:src="@drawable/ic_launcher" />


2.自定义下载类,ConnectWeb.java

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;

public class ConnectWeb {
//几种消息
protected static final int PICOK = 0;
protected static final int PICFAIL = 1;
protected static final int MP3OK = 2;
protected static final int MP3FAIL = 3;
protected static final int DOWNOK = 4;
protected static final int DOWNFAIL = 5;

private Handler handler;
private Context context;

public ConnectWeb(Context context, Handler handler) {
this.context = context;
this.handler = handler;
}

public void getPicture() {
new Thread() {
public void run() {
String url = "http://192.168.7.191:8080/ql/111.gif";//资源地址
Bitmap bitmap = null;
Message msg = Message.obtain();
try {
URL picUrl = new URL(url);//实例化URL对象
HttpURLConnection conn = (HttpURLConnection) picUrl.openConnection();//打开连接
conn.connect();
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {//如果请求成功
InputStream is = conn.getInputStream();//读取资源数据
bitmap = BitmapFactory.decodeStream(is);
msg.obj = bitmap;
msg.what = PICOK;
}
} catch (MalformedURLException e) {
e.printStackTrace();
msg.what = PICFAIL;
} catch (IOException e) {
e.printStackTrace();
msg.what = PICFAIL;
}
handler.sendMessage(msg);//发消息
}
}.start();
}

public void getMp3() {
new Thread() {
public void run() {
String url = "http://192.168.7.191:8080/ql/BigGirlsCry.mp3";//资源url
Message msg = Message.obtain();//从消息池中获取消息对象,避免重复创建
try {
URL picUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) picUrl.openConnection();// 阻塞
conn.connect();
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
msg.what = MP3OK;
msg.obj = conn;
}
} catch (MalformedURLException e) {
e.printStackTrace();
msg.what = MP3FAIL;
} catch (IOException e) {
e.printStackTrace();
msg.what = MP3FAIL;
}
handler.sendMessage(msg);
}
}.start();
}

public void downloadMp3(final HttpURLConnection conn, final Handler handler) {
if (conn == null) {
return;
}

// 设置进度对话框
final ProgressDialog pd = new ProgressDialog(context);
pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pd.setTitle("下载中");
pd.setMessage("正在下载...");
pd.show();

// 启动下载线程
new Thread() {
public void run() {
byte[] bytes = null;
int dowloadsize = 0;
// 获得下载MP3文件的大小
int fileSize = conn.getContentLength();
// 设置下载缓冲区,因为文件大,不能一口气读写完
if (fileSize - dowloadsize > 4096) {
bytes = new byte[4096];
} else {
bytes = new byte[fileSize - dowloadsize];
}
// 设置进度值
pd.setMax(fileSize);
pd.setProgress(0);

// 获得输入流
try {
int len = -1;
InputStream is = conn.getInputStream();
// 写SD卡路径
File file = new File(Environment.getExternalStorageDirectory().getPath() + File.separator
+ "mp3" + File.separator + "dearme.mp3");
// 创建下载音乐的目录
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
// 写sd的文件流
OutputStream os = new FileOutputStream(file);
while ((len = is.read(bytes)) != -1) {
dowloadsize += len;
if (dowloadsize != fileSize) {
pd.setProgress(dowloadsize);
Thread.sleep(100);
} else {
pd.dismiss();
}
os.write(bytes, 0, len);
}
os.flush();
os.close();
is.close();
handler.sendEmptyMessage(DOWNOK);

} catch (IOException e) {
e.printStackTrace();
handler.sendEmptyMessage(DOWNFAIL);
} catch (InterruptedException e) {
e.printStackTrace();
handler.sendEmptyMessage(DOWNFAIL);
}
}
}.start();
}
}


3.活动MainActivity

public class MainActivity extends Activity implements OnClickListener {
protected static final int PICOK = 0;
protected static final int PICFAIL = 1;
protected static final int MP3OK = 2;
protected static final int MP3FAIL = 3;
protected static final int DOWNOK = 4;
protected static final int DOWNFAIL = 5;

ConnectWeb connectWeb;//访问网络的自定义外部类
ImageView imageView;
MediaPlayer mediaPlayer;

//用handler收发信息
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case PICOK:
Bitmap bitmap = (Bitmap) msg.obj;//获取消息发过来的对象
imageView.setImageBitmap(bitmap);//显示在imageView上
break;
case PICFAIL:
Toast.makeText(MainActivity.this, "下载图片失败!", Toast.LENGTH_SHORT)
.show();
break;
case MP3OK:
HttpURLConnection conn = (HttpURLConnection) msg.obj;//资源请求成功的资源对象
connectWeb.downloadMp3(conn, handler);//使用下载方法
break;
case MP3FAIL:
case DOWNFAIL:
Toast.makeText(MainActivity.this, "下载MP3失败!",
Toast.LENGTH_SHORT).show();
break;
case DOWNOK:
//测试用
//下载好了播放出来
try {
mediaPlayer = new MediaPlayer();
mediaPlayer.reset();
mediaPlayer.setDataSource(Environment.getExternalStorageDirectory()
.getPath() + File.separator + "mp3" + File.separator + "dearme.mp3");
mediaPlayer.prepare();
mediaPlayer.start();
} catch (Exception e) {
e.printStackTrace();
}
break;

default:
break;
}
}
};

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
imageView = (ImageView) findViewById(R.id.imageView1);
connectWeb = new ConnectWeb(this, handler);

Button button = (Button) findViewById(R.id.button1);
Button button2 = (Button) findViewById(R.id.button2);
button.setOnClickListener(this);
button2.setOnClickListener(this);
}

@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
connectWeb.getPicture();//封装的获取图片方法
break;
case R.id.button2:
connectWeb.getMp3();//封装的获取歌曲方法
break;

default:
break;
}
}

@Override
protected void onDestroy() {
super.onDestroy();
mediaPlayer.release();//释放资源
}
}


4.添加网络访问和sd卡读写权限

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


1.2使用异步任务方法(异步任务不会阻塞UI),进行多个下载任务

活动java代码:

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;

/**
* 使用异步任务进行网络资源下载
*
* @author qinlang
*
*/
public class MainActivity extends Activity implements OnClickListener{
ImageView imgv1, imgv2, imgv3, imgv4;
//地址数组
String[] urls = { "http://192.168.11.146:8080/ql/222.jpg",
"http://192.168.11.146:8080/ql/222.jpg",
"http://192.168.11.146:8080/ql/222.jpg",
"http://192.168.11.146:8080/ql/222.jpg"};

private Button button;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
imgv1 = (ImageView) findViewById(R.id.imageView1);
imgv2 = (ImageView) findViewById(R.id.imageView2);
imgv3 = (ImageView) findViewById(R.id.imageView3);
imgv4 = (ImageView) findViewById(R.id.imageView4);

button = (Button) findViewById(R.id.button1);
button.setOnClickListener(this);
}

//异步类
class ImageAsyncTask extends AsyncTask<String, Integer, Bitmap> {
ImageView imageView;

public ImageAsyncTask(ImageView imageView) {
this.imageView = imageView;
}

@Override//后台处理
protected Bitmap doInBackground(String... params) {
String imgUrl = params[0];//得到地址
try {
URL picUrl = new URL(imgUrl);//实例化URL对象
HttpURLConnection conn = (HttpURLConnection) picUrl
.openConnection();//打开连接
conn.connect();//连接
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
InputStream is = conn.getInputStream();//得到资源
return BitmapFactory.decodeStream(is);
}
} catch (MalformedURLException e) {
e.printStackTrace();

} catch (IOException e) {
e.printStackTrace();
}
return null;
}

@Override//前台处理
protected void onPostExecute(Bitmap result) {
if (result != null) {
imageView.setImageBitmap(result);//更新ui
}
}
}

@Override
public void onClick(View v) {
ImageAsyncTask task = null;
switch (v.getId()) {
case R.id.button1:
//四个异步任务下载图片
for (int i = 0; i < urls.length; i++) {
String url = urls[i];
switch (i) {
case 0:
task = new ImageAsyncTask(imgv1);
task.execute(url);
break;
case 1:
task = new ImageAsyncTask(imgv2);
task.execute(url);
break;
case 2:
task = new ImageAsyncTask(imgv3);
task.execute(url);
break;
case 3:
task = new ImageAsyncTask(imgv4);
task.execute(url);
break;
default:
break;
}
}
break;

default:
break;
}
}
}


示例2:

访问网络服务器,与服务器进行交互数据

android客户端利用web服务器上jsp页面来实现用户登录验证

url=http://192.168.7.5:8080/myweb/mylogin.jsp?userName=tom&password=cat

1.服务器jsp网页

<%@ page contentType="text/html; charset=utf-8" language="java" errorPage="" %>
<%
String name = request.getParameter("userName");
String pass = request.getParameter("password");
System.out.println("userName:"+name);
System.out.println("password:"+pass);
if (name.equals("tom")
&& pass.equals("cat"))
{
session.setAttribute("user" , name);
out.println("恭喜您,登录成功!");
}
else
{
out.println("对不起,用户名、密码不符合!");
}
%>


2.1使用get请求方式

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity {
EditText user,pwd;
TextView txtResult;
String url;
HttpClient client;
HttpGet request;
HttpResponse response;

//使用handler收发消息
Handler handler=new Handler(){
public void handleMessage(Message msg) {
txtResult.setText(msg.obj.toString());//将结果显示出来
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.face);
user=(EditText)findViewById(R.id.editUser);
pwd=(EditText)findViewById(R.id.editPWD);
txtResult=(TextView)findViewById(R.id.txtResult);
}

public void doButton(View view){
switch (view.getId()) {
case R.id.button1:
login(user.getText().toString().trim(),pwd.getText().toString().trim());

break;
case R.id.button2:

break;
default:
break;
}
}

//封装的登陆方法
private void login(String usr, String pwd) {
url="http://192.168.7.5:8080/myweb2/mylogin.jsp";
//get请求要附加参数
url=url+"?userName="+usr+"&password="+pwd;

//1.步骤1
client=new DefaultHttpClient();
//2.步骤2
request=new HttpGet(url);
//3.步骤3

new Thread(){
public void run() {
String result="";
Message msg=Message.obtain();
try {
response=client.execute(request);

if(response.getStatusLine().getStatusCode()==HttpStatus.SC_OK){//如果请求成功
result=EntityUtils.toString(response.getEntity());//使用工具类将结果取出
}else{
result="Error Response:"+response.getStatusLine().getStatusCode();//错误的结果码
}
msg.obj=result;//将结果发回去

} catch (ClientProtocolException e) {
e.printStackTrace();
msg.obj="http connect fail";
} catch (IOException e) {
e.printStackTrace();
msg.obj="http connect fail";
}
handler.sendMessage(msg);//发送消息
}
}.start();

}
}


2.2使用post请求方式

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity {
EditText user,pwd;
TextView txtResult;
String url;
HttpClient client;
HttpPost request;
HttpResponse response;
Handler handler=new Handler(){
public void handleMessage(Message msg) {
txtResult.setText(msg.obj.toString());
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.face);
user=(EditText)findViewById(R.id.editUser);
pwd=(EditText)findViewById(R.id.editPWD);
txtResult=(TextView)findViewById(R.id.txtResult);
}

public void doButton(View view){
switch (view.getId()) {
case R.id.button1:
login(user.getText().toString().trim(),pwd.getText().toString().trim());

break;
case R.id.button2:

break;
default:
break;
}
}

private void login(String usr, String pwd) {
//不带参数的post请求
url="http://192.168.7.5:8080/myweb/mylogin.jsp";
//1.
client=new DefaultHttpClient();
//2.
request=new HttpPost(url);
//3.使用键值对将参数封装
final List<NameValuePair> params=new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("userName", usr));
params.add(new BasicNameValuePair("password",pwd)) ;

new Thread(){
public void run() {
String result="";
Message msg=Message.obtain();
try {
request.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));//设置Entity并转换编码格式(服务器是utf-8的)

response=client.execute(request);//执行提交

if(response.getStatusLine().getStatusCode()==HttpStatus.SC_OK){
result=EntityUtils.toString(response.getEntity());//使用工具类取出对象(工具类在org.apache.http.util.EntityUtils包中)
}else{
result="Error Response:"+response.getStatusLine().getStatusCode();
}
msg.obj=result;

} catch (ClientProtocolException e) {
e.printStackTrace();
msg.obj="http connect fail";
} catch (IOException e) {
e.printStackTrace();
msg.obj="http connect fail";
}
handler.sendMessage(msg);
}
}.start();

}
}


3.JSon部分

了解JSON相关知识请移步:JSON 数据格式解析

更多Json例子请移步:JAVA基础学习之Http(含JSON)网络编程

相关类:

android 自带内置的json 工具类位于org.json包

JSONObject 类

JSONArray 类

示例:

1.xml布局

<Button
android:id="@+id/btnGet"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="获得服务端的json数据" />
<ScrollView
android:id="@+id/scrollView1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >

<LinearLayout
android:id="@+id/linearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TextView" />

</LinearLayout>
</ScrollView>


2.定义一个数据bean类,FoodData.java

public class FoodData {
private int id;
private String name;
private int price;
private int type;

public FoodData(int id, String name, int price, int type) {
this.id = id;
this.name = name;
this.price = price;
this.type = type;
}

public FoodData() {

}

public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}

@Override
public String toString() {
return "id:"+id+",name:"+name+",price:"+price+",type:"+type;
}
}


3.活动MainActivity代码

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends ActionBarActivity {
//protected static final String TAG = "robin debug";
Button getbtn;
TextView tv;
Handler handler=new Handler(){

@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 1:
List<FoodData> list=(List<FoodData>) msg.obj;
StringBuilder builder=new StringBuilder("从服务器获得的数据\n");
for(int i=0;i<list.size();i++){
builder.append(list.get(i).toString()+"\n");
}
tv.setText(builder.toString());
break;
case -1:
break;
default:
break;
}
}
};

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

tv=(TextView)findViewById(R.id.textView1);
getbtn=(Button)findViewById(R.id.btnGet);
getbtn.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
getFoodList();
}
});
}

protected void getFoodList() {
new Thread(){
public void run(){
String url="http://192.168.7.5:8080/myweb/GetJsonData";
HttpPost request=new HttpPost(url);//post请求
HttpResponse response;
List<FoodData> list=null;
Message msg=Message.obtain();
try {
//发送请求
response=new DefaultHttpClient().execute(request);
if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
String jsonString=EntityUtils.toString(response.getEntity());

//Log.e(TAG, ""+jsonString);
list=getFoodData(jsonString);//解析json字符串
msg.what=1;
msg.obj=list;
}

} catch (ClientProtocolException e) {
e.printStackTrace();
msg.what=-1;
} catch (IOException e) {
e.printStackTrace();
msg.what=-1;
}
handler.sendMessage(msg);
}
}.start();
}

protected List<FoodData> getFoodData(String jsonString) {
List<FoodData> foodList=new ArrayList<FoodData>();

try {
JSONObject obj=new JSONObject(jsonString);
JSONArray array=obj.getJSONArray("carte");
//Log.e(TAG, ""+array.length());

for(int i=0;i<array.length();i++){
JSONObject o=(JSONObject) array.get(i);
FoodData foodData=new FoodData();
foodData.setId(o.getInt("id"));
foodData.setPrice(o.getInt("prices"));
foodData.setName(o.getString("name"));
foodData.setType(o.getInt("type"));
foodList.add(foodData);
}
} catch (JSONException e) {
e.printStackTrace();
}
return foodList;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息