DoRemix 2013-09-26 08:40 采纳率: 0%
浏览 1298

谁能帮我解释下 这个代码 然后最好能让里面数据显示到listview中去

package com.httppost.main;

import java.io.IOException;
import java.io.InterruptedIOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class HttpPostActivity extends Activity {
TextView textView;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main); //获取main这个页面
Button jsonBtn = (Button) findViewById(R.id.get_array_json); //获取组件
jsonBtn.setOnClickListener(jsonClick); //监听按键
Button listBtn = (Button) findViewById(R.id.get_list_json);

    listBtn.setOnClickListener(listClick);
}

//获取单个json封装的数据
OnClickListener jsonClick = new OnClickListener() { //按键事件

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        ProgressDialog proDialog = ProgressDialog.show(v.getContext(), "",
                "正在获取数据……", true, true);                                    //显示dialong
        HttpThread jsonThread = new HttpThread(v.getContext(), proDialog);      // 创建一个Http线程 
        String url = "http://birsys.ceshiceshi.com/json_1.php";                 //创建URL
        // url传递参数                                                              
        String[] key = { "type" };                                              //传递参数          
        String[] value = { "0" };                                                   
        // php页面返回的json键
        String[] jsonKey = { "id", "username", "lat", "lon","type" };
        //传递相应的参数
        jsonThread.setUrl(url);
        jsonThread.setKey(key);
        jsonThread.setValue(value);
        jsonThread.setJsonKey(jsonKey);
        jsonThread.start();
        textView= (TextView)findViewById(R.id.textview);
        textView.setText(url);
    }
};

//获取带数组类型的封装
OnClickListener listClick = new OnClickListener() {

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        ProgressDialog proDialog = ProgressDialog.show(v.getContext(), "",
                "正在获取数据……", true, true);
        HttpThread jsonThread = new HttpThread(v.getContext(), proDialog);
        String url = "http://birsys.ceshiceshi.com/json_2.php";
        // url传递参数
        String[] key = { "type" };
        String[] value = { "1" };
        // php页面返回的json键
        String[] jsonKey = { "id", "username", "lat", "lon","type" };
        String jsonName="json_2";
        //传递相应的参数
        jsonThread.setUrl(url);
        jsonThread.setKey(key);
        jsonThread.setValue(value);
        jsonThread.setJsonName(jsonName);
        jsonThread.setJsonKey(jsonKey);
        jsonThread.start();

    }
};

public class Json {

    // 解析单一的json封装,并返回字符串数组
    /**
     * 参数说明: 
     * 1.webContent 获取的网页封装的json格式数据 
     * 2.key 以数组形式组成的json的键名称
     * */
    public String[] getJSON(String webContent, String[] key) {
        int size = key.length;
        String[] s = new String[size];
        try {
            JSONObject jsonObject = new JSONObject(webContent);
            for (int j = 0; j < size; j++) {
                s[j] = jsonObject.getString(key[j]);
                System.out.println(key[j] + "===string==="
                        + jsonObject.getString(key[j]));
            }
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            s = null;
        }
        return s;
    }

    // 获取数组型的结构,返回ArrayList<HashMap<String, Object>>,方便listview中填充数据
    /**
     * 参数说明: 
     * 1.webContent 获取的网页封装的json格式数据
     * 2.key 以数组形式组成的json的键名称 3.jsonName
     * 封装json数组数据的json名称
     *

    public ArrayList<HashMap<String, Object>> getJSONArray(String webContent,
            String[] key, String jsonName) {
        ArrayList<HashMap<String, Object>> list;
        JSONArray jsonObject;
        try {
            jsonObject = new JSONObject(webContent).getJSONArray(jsonName);
            list = new ArrayList<HashMap<String, Object>>();
            for (int i = 0; i < jsonObject.length(); i++) {
                JSONObject jsonObject2 = (JSONObject) jsonObject.opt(i);
                HashMap<String, Object> map = new HashMap<String, Object>();
                for (int j = 0; j < key.length; j++) {
                    map.put(key[j], jsonObject2.getString(key[j]));
                    System.out.println(key[j] + "==="
                            + jsonObject2.getString(key[j]));
                }
                list.add(map);
            }

        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            list = null;
        }
        return list;
    } */
}

public class HttpThread extends Thread{

    private Context context;
    private ProgressDialog proDialog;
    private String url;
    private String []key;
    private String []value;
    private String []jsonKey;
    private String jsonName;
    private String []array;
    ArrayList<HashMap<String, Object>> list;

    public HttpThread(Context context,ProgressDialog proDialog){
        this.context=context;
        this.proDialog=proDialog;
    }

    @Override
    public void run(){
        Message msg = handler.obtainMessage();
        HttpPostRequest post=new HttpPostRequest();     
        int res=post.requestHttp(url, key, value);
        String webContent=post.getWebContext();
        msg.what=res;
        if(res==1){
            //解析json
            Json json=new Json();
            if(jsonName!=null)
                //解析数组型的json
                //list=json.getJSONArray(webContent, jsonKey, jsonName);
            //else
                //解析单个json值
                array=json.getJSON(webContent, jsonKey);
        }       
        handler.sendMessage(msg);   
    }
    private Handler handler = new Handler() {
        // TODO Auto-generated constructor stub
        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            super.handleMessage(msg);           
            int what=msg.what;
            Http_Status_Tips status=new Http_Status_Tips();
            //返回成功数据时
            if(what==1){
                //处理数组型json
                if(list!=null){
                    int size=list.size();
                    String result="";
                    for(int i=0;i<size;i++){
                        int s=jsonKey.length;
                        //迭代jsonKey数组值
                        for(int j=0;j<s;j++){
                            result+=jsonKey[j]+":"+list.get(i).get(jsonKey[j])+"\n";
                        }
                        result+="\n";                       
                    }
                    Toast.makeText(context, result, Toast.LENGTH_LONG).show();  

                }
                //处理单个字符json
                if(array!=null){
                    int arraySize=array.length;
                    String rs="";
                    for(int k=0;k<arraySize;k++){
                        rs+=jsonKey[k]+":"+array[k]+"\n";                       
                    }
                    Toast.makeText(context, rs, Toast.LENGTH_LONG).show();
                    if(array[0].equals("2"))
                        Toast.makeText(context, array[0], Toast.LENGTH_LONG).show();
                }               
            }
            //根据服务器端返回数据,自定义提示
            else if(what==2){
                status.setTips("自定义提示2");
            }//根据服务器端返回数据,自定义提示
            else if(what==3){
                status.setTips("自定义提示3");
            }
            status.ShowHttpStatusTips(what, context,proDialog);             
        }       
    };

    //activity界面传递的参数
    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String[] getKey() {
        return key;
    }

    public void setKey(String[] key) {
        this.key = key;
    }

    public String[] getValue() {
        return value;
    }

    public void setValue(String[] value) {
        this.value = value;
    }

    public String[] getJsonKey() {
        return jsonKey;
    }

    public void setJsonKey(String[] jsonKey) {
        this.jsonKey = jsonKey;
    }

    public String getJsonName() {
        return jsonName;
    }

    public void setJsonName(String jsonName) {
        this.jsonName = jsonName;
    }
}



public class HttpPostRequest {

    private String webContext;
    //返回请求内容
    public String getWebContext() {
        return webContext;
    }
    public void setWebContext(String webContext) {
        this.webContext = webContext;
    }
    //该函数返回服务器访问的各种状态,并通过webContext传递获取的文本值
    /**
     * 参数说明
     * url 访问的网络地址
     * key 传递参数的名称
     * value 传递参数的值
     * key 与value数组长度对应,即一对键值对,这样可以不限制参数传递的个数
     * */
    public int requestHttp(String url,String []key,String []value) {
        // TODO Auto-generated method stub
        int status = 0;
        DefaultHttpClient mHttpClient = new DefaultHttpClient();
        HttpPost mPost = new HttpPost(url);
        List<BasicNameValuePair> pairs = new ArrayList<BasicNameValuePair>();
        int size=key.length;
        for(int i=0;i<size;i++){
            pairs.add(new BasicNameValuePair(key[i], value[i]));            
        }
        try {
            mPost.setEntity(new UrlEncodedFormEntity(pairs, HTTP.UTF_8));
        } catch (UnsupportedEncodingException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        try {
            mHttpClient.getParams().setIntParameter(HttpConnectionParams.SO_TIMEOUT, 60000); // Socket超时设置60s
            mHttpClient.getParams().setIntParameter(HttpConnectionParams.CONNECTION_TIMEOUT, 60000);// 连接超时60s
            HttpResponse response = mHttpClient.execute(mPost);
            int res = response.getStatusLine().getStatusCode();         
            if (res == 200) {               
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    String info = EntityUtils.toString(entity);
                    setWebContext(info);
                    status=1;
                }
            } else if (res == 404) {
                status = 404;
            } else if (res == 500) {
                status = 500;
            }
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            status = 900;
        } catch (ConnectTimeoutException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            status = 901;
        } catch (InterruptedIOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            status = 902;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            status = 903;
        }
        return status;
    }
}
public class Http_Status_Tips {
    //服务器端返回的状态提示
    public static final String HTTP_0="其他错误";
    public static final String HTTP_1="";
    public static final String HTTP_404="404错误,请求链接无效";
    public static final String HTTP_500="网络500错误,服务器端程序出错";
    public static final String HTTP_900="网络传输协议出错";
    public static final String HTTP_901="连接超时";
    public static final String HTTP_902="网络中断";
    public static final String HTTP_903="网络数据流传输出错";
    public static final String HTTP_UNKONW="未知的错误";

    //自定义的提示
    private String tips;

    public  void ShowHttpStatusTips(int status,Context context,ProgressDialog proDialog){
        switch(status){
        case 0:
            Toast.makeText(context, getTips(), Toast.LENGTH_LONG).show();
            break;
        case 1:
            //Toast.makeText(context, getTips(), Toast.LENGTH_LONG).show();
            break;
        case 2:
            Toast.makeText(context, getTips(), Toast.LENGTH_LONG).show();
            break;
        case 3:
            Toast.makeText(context, getTips(), Toast.LENGTH_LONG).show();
            break;
        case 404:
            Toast.makeText(context, HTTP_404, Toast.LENGTH_LONG).show();

            break;
        case 500:
            Toast.makeText(context, HTTP_500,Toast.LENGTH_LONG).show();         
            break;
        case 900:
            Toast.makeText(context, HTTP_900, Toast.LENGTH_LONG).show();            
            break;
        case 901:
            Toast.makeText(context, HTTP_901, Toast.LENGTH_LONG).show();
            break;
        case 902:
            Toast.makeText(context, HTTP_902, Toast.LENGTH_LONG).show();
            break;
        case 903:
            Toast.makeText(context, HTTP_903, Toast.LENGTH_LONG).show();
            break;
        default:
            Toast.makeText(context, HTTP_UNKONW, Toast.LENGTH_LONG).show();
            break;          
        }
        if(proDialog!=null)
            proDialog.dismiss();
    }

    public String getTips() {
        return tips;
    }
    public void setTips(String tips) {
        this.tips = tips;
    }

}

}

  • 写回答

1条回答

  • 专家-赤兔[在线] 全栈领域优质创作者 2023-09-27 11:16
    关注

    该回复引自免费微信小程序-皆我百晓生:


    这段代码是一个Android应用程序,用于从服务器获取JSON数据,并将数据显示在ListView中。

    首先,这段代码创建了一个名为HttpPostActivity的Activity类。在onCreate方法中,它设置了布局文件为main.xml,并获取了两个按钮:get_array_json和get_list_json,并为它们分别设置了点击事件的监听器。

    点击get_array_json按钮时,会创建一个ProgressDialog对话框来显示正在获取数据的提示信息。然后,创建一个HttpThread线程,并传入上下文和ProgressDialog对象。接下来,设置URL、参数和JSON键,并启动线程。最后,将获取到的URL显示在TextView中。

    点击get_list_json按钮时,会执行类似的操作,但是获取的是带有数组类型的封装数据。

    HttpThread类是一个自定义的线程类,用于发送HTTP请求并获取服务器返回的JSON数据。它使用Apache HttpClient库来发送POST请求,并使用JSON解析库来解析返回的JSON数据。在run方法中,它首先创建一个DefaultHttpClient对象,并设置连接超时时间。然后,创建一个HttpPost对象,并设置URL和参数。接下来,发送请求并获取响应。最后,解析JSON数据,并将解析后的数据发送给主线程。

    在主线程中,通过Handler来处理从HttpThread线程发送过来的消息。在handleMessage方法中,根据消息的类型进行相应的处理。对于获取到的JSON数据,可以将其显示在ListView中。

    要将数据显示在ListView中,你需要创建一个适配器(Adapter),并将数据传递给适配器。然后,将适配器设置给ListView。适配器负责将数据绑定到ListView的每个项上。

    希望这能帮到你理解这段代码。如果你有任何进一步的问题,请随时提问。

    评论

报告相同问题?

悬赏问题

  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示