如何从特定的URL读取json对象?

时间:2015-10-24 09:11:43

标签: android json

  

我想在特定源url的视图上的相应文本字段中显示Json对象。我想读取此对象并在文本字段中单独显示。

1 个答案:

答案 0 :(得分:-1)

    package com.mcommerce.webservices;

    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    import java.io.OutputStreamWriter;
    import java.net.HttpURLConnection;
    import java.net.URL;
    import org.json.JSONObject;
    import com.mcommerce.networkconnection.NetworkUtil;
    import android.content.Context;
    import android.util.Log;

    public class Connection {
        Context context;
        HttpURLConnection urlconnection=null;
        URL url;
        String method="";
        StringBuilder sb;
        String result="";
        int httpResult;

        public Connection(Context context,URL url,String method){
            this.context=context;
            this.url=url;
            this.method=method;
        }
        public HttpURLConnection createConnection(){

            try{
                NetworkUtil network_util=new NetworkUtil();
                int networkStatus=network_util.getConnectivityStatus(context);
                if(networkStatus!=0)
                {
                    urlconnection=(HttpURLConnection)url.openConnection();      
                }
                else{

                }
            }catch(Exception e){
                Log.e("Can't create connections", e.getMessage());

            }

            return urlconnection;

        }
        public String doFunctionGET(){

            try{
                urlconnection=createConnection();
                urlconnection.setDoInput(true);
                urlconnection.setRequestMethod(method);
                urlconnection.setUseCaches(false);
                urlconnection.setConnectTimeout(10000);
                urlconnection.setReadTimeout(10000);
                urlconnection.setRequestProperty("Content-Type", "application/json");
                urlconnection.connect();

                httpResult=urlconnection.getResponseCode();
                System.out.println("Response Code"+ httpResult);
                result=readResponse();      
                System.out.println("obtained result"+result);

            }catch(Exception e){
                Log.e("Response Error", e.getMessage());
            }
            finally{
                removeConnection();
            }

            return result;
        }
        public String doFunctionPost(JSONObject object){
            try{
                urlconnection=createConnection();
                urlconnection.setDoInput(true);
                urlconnection.setDoOutput(true);
                urlconnection.setRequestMethod(method);
                urlconnection.setUseCaches(false);
                urlconnection.setConnectTimeout(10000);
                urlconnection.setReadTimeout(10000);
                urlconnection.setRequestProperty("json", object.toString());
                urlconnection.setRequestProperty("Content-Type", "application/json");

                OutputStreamWriter out=new OutputStreamWriter(urlconnection.getOutputStream());
                out.write(object.toString());
                   System.out.println(object.toString());
                    out.close();
                    httpResult=urlconnection.getResponseCode();
                    System.out.println("Response Code"+ httpResult);
                    result=readResponse();

            }catch(Exception e){
                Log.e("Response Error", e.getMessage());

            }finally{
                removeConnection();
            }
            return result;
        }
        public String readResponse(){
            try{
                if(httpResult==HttpURLConnection.HTTP_OK){
                    BufferedReader buffer_reader=new BufferedReader(new InputStreamReader(urlconnection.getInputStream(),"utf-8"));
                    String line=null;
                    sb=new StringBuilder();
                    while((line=buffer_reader.readLine())!=null){
                        sb.append(line+"\n");
                    }
                    buffer_reader.close();
                    System.out.println("buffer_reader"+sb.toString());
                }else{
                    Log.e("Error on posting", urlconnection.getResponseMessage());
                }
            }catch(Exception e){
                Log.e("Error in Response", e.getMessage());
            }
            return sb.toString();
        }
        public void removeConnection(){
            if(urlconnection!=null){
                urlconnection.disconnect();
            }
        }
    }




public class ServiceFunctions {
    Context context;
    String result="";
    GetUrl get_url=new GetUrl();
    Connection con;
    String method_post="POST";
    String method_get="GET";

    ArrayList<ProductList> product_list;

public ServiceFunctions(Context context){
        this.context=context;
    }
    public String loginResult(String username,String password){
        String login_result=null;
        try{
            URL url=get_url.getLoginURL();
            con= new Connection(context, url, method_post);
            JSONObject object=new JSONObject();
            object.put("username", username);
            object.put("password", password);

            JSONObject obj=new JSONObject();
            obj.put("login_details", object);       
            System.out.println(obj);
            result=con.doFunctionPost(obj);



            JSONObject json_result_object=new JSONObject(result);
            JSONObject sub_obj=json_result_object.getJSONObject("login_details");
            System.out.println(sub_obj);

            login_result=sub_obj.getString("status");
            if(login_result.equalsIgnoreCase("success")){
                int user_id=sub_obj.getInt("id_customer");
                System.out.println(user_id);
                DataMembers.customer_id=user_id;
            }else{

            }

        }catch(Exception e){
            e.printStackTrace();
        }   
        return login_result;
    }
public void getProductDetails(int category_id){
        product_list=new ArrayList<ProductList>();

        try{
        URL url=get_url.getProductListUrl(category_id);
        con=new Connection(context,url,method_get);
        result=con.doFunctionGET();
        JSONObject main_object=new JSONObject(result);
        JSONArray array=new JSONArray(main_object.getString("Product_list"));
        for(int i=0;i<array.length();i++){
            JSONObject object=array.getJSONObject(i);
            ProductList product_list_object=new ProductList();
            //product_list.setProduct_id(Integer.parseInt(object.getString("product_id")));
            product_list_object.setProduct_name(object.getString("Product Name"));
            product_list_object.setProduct_image(object.getString("Image src"));
            product_list_object.setProduct_price(object.getString("Price"));
            product_list.add(product_list_object);

        }
            DataMembers.productlist=product_list;

        }catch(Exception e){
            e.printStackTrace();
        }
    }
}




package com.mcommerce.networkconnection;

import java.net.URL;

public class GetUrl {
    URL url;        
    public static String login_url="http://192.168.1.138/webservices/final1.php";
    public static String product_list_url="http://192.168.1.138/webservices/prod_list.php";
    public URL getLoginURL(){
        url=getURL(login_url);
        return url;
    }


    public URL getProductListUrl(int category_id){
        url=getURL(product_list_url+"?id_category="+category_id);
        return url;
    }

    public URL getURL(String url){
        URL _url=null;      
        try{
            _url=new URL(url);
        }catch(Exception e){
            e.printStackTrace();
        }
        return _url;
    }
}





import com.mcommerce.taskinterface.UICallback;
import com.mcommerce.webservices.ServiceFunctions;


import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;

public class GetProductList extends AsyncTask<Void, Void, Void>{

    Context context;
    UICallback callback;
    int category_id;
      ProgressDialog pgdialog;
        ServiceFunctions functions;
    public GetProductList(Context context,UICallback callback,int category_id) {
        // TODO Auto-generated constructor stub
        this.context=context;
        this.callback=callback;
        this.category_id=category_id;
    }
    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        pgdialog=new ProgressDialog(context);
        pgdialog.setMessage("Loading...");
        pgdialog.setCanceledOnTouchOutside(false);
        pgdialog.show();
    }
    @Override
    protected Void doInBackground(Void... params) {
        // TODO Auto-generated method stub
        functions=new ServiceFunctions(context);
        functions.getProductDetails(category_id);
        return null;
    }
    @Override
    protected void onPostExecute(Void result) {
        // TODO Auto-generated method stub
        pgdialog.dismiss();
        callback.onComplete("success");
    }

}