本文介绍了如何使用JSON使用POST方法在android系统的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经创建了使用JSON的Andr​​oid应用程序从ROR网站获得,并在列表视图中显示,现在,我想从我们的应用程序添加数据,它也已经在我们的应用程序的列表视图中显示,然后它来显示网站also.How使用POST方法,并显示在我们的应用程序。

让我的方法使用像

 公共类MainActivity扩展ListActivity实现FetchDataListener
{
    私人ProgressDialog对话框;    @覆盖
    保护无效的onCreate(捆绑savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.activity_list_item);
        initView();
    }    私人无效initView()
    {
        //显示进度对话框
        对话框= ProgressDialog.show(这一点,,载入中...);
        字符串URL =htt​​p://floating-wildwood-1154.herokuapp.com/posts.json;
        FetchDataTask任务=新FetchDataTask(本);
        task.execute(URL);
    }    @覆盖
    公共无效onFetchComplete(列表<应用>数据)
    {
        //驳回进度对话框
        如果(对话!= NULL)
            dialog.dismiss();
        //创建新的适配器
        ApplicationAdapter适配器=新ApplicationAdapter(这个数据);
        //设置适配器列表
        setListAdapter(适配器);
    }    @覆盖
    公共无效onFetchFailure(弦乐味精)
    {
        //驳回进度对话框
        如果(对话!= NULL)
            dialog.dismiss();
        //显示故障信息
        Toast.makeText(这一点,味精,Toast.LENGTH_LONG).show();
    }
}

fetchdatatask.java

 公共类FetchDataTask扩展的AsyncTask<弦乐,太虚,字符串>
{
    私人最终FetchDataListener侦听器;
    私人弦乐味精;    公共FetchDataTask(FetchDataListener监听器)
    {
        this.listener =侦听器;
    }    @覆盖
    保护字符串doInBackground(字符串... PARAMS)
    {
        如果(PARAMS == NULL)
            返回null;
        //从PARAMS网址
        字符串URL =参数[0];
        尝试
        {
            //创建http连接
            HttpClient的客户端=新DefaultHttpClient();
            HTTPGET HTTPGET =新HTTPGET(URL);
            //连接
            HTT presponse响应= client.execute(HTTPGET);
            //获取响应
            HttpEntity实体= response.getEntity();
            如果(实体== NULL)
            {
                味精=从服务器无响应;
                返回null;
            }
            //获取响应内容并将其转换为JSON字符串
            InputStream为= entity.getContent();
            返回streamToString(是);
        }
        赶上(IOException异常E)
        {
            味精=无网络连接;
        }
        返回null;
    }    @覆盖
    保护无效onPostExecute(字符串sJson)
    {
        如果(sJson == NULL)
        {
            如果(听众!= NULL)
                listener.onFetchFailure(MSG);
            返回;
        }
        尝试
        {
            // JSON字符串转换成JSON对象
            的JSONObject的JSONObject =新的JSONObject(sJson);
            JSONArray aJson = jsonObject.getJSONArray(后);
            //创建应用列表
            清单<应用>应用=新的ArrayList<应用>();
            的for(int i = 0; I< aJson.length();我++)
            {
                JSONObject的JSON = aJson.getJSONObject(I)
                应用程序=新的应用程序();
                app.setContent(json.getString(内容));
                //应用程序添加到应用列表
                apps.add(应用);
            }
            //通知取数据的活动已经完成
            如果(听众!= NULL)
                listener.onFetchComplete(应用);
        }
        赶上(JSONException E)
        {
            e.printStackTrace();
            味精=无效的反应;
            如果(听众!= NULL)
                listener.onFetchFailure(MSG);
            返回;
        }
    }    / **
     *此功能将响应流转换成JSON字符串
     *
     * @参数是
     * respons串
     * @返回JSON字符串
     *引发IOException
     * /
    公共字符串streamToString(最终InputStream为)抛出IOException异常
    {
        读者的BufferedReader =新的BufferedReader(新的InputStreamReader(是));
        StringBuilder的SB =新的StringBuilder();
        串线= NULL;
        尝试
        {
            而((行= reader.readLine())!= NULL)
            {
                sb.append(行+\\ n);
            }
        }
        赶上(IOException异常E)
        {
            Ë扔掉;
        }
        最后
        {
            尝试
            {
                is.close();
            }
            赶上(IOException异常E)
            {
                Ë扔掉;
            }
        }
        返回sb.toString();
    }
}

喜欢我现在用GET方法也显示,对于同样的目的,我想POST方法添加到Android的ListView中显示,并在网站上也显示。

如果我将创建一个按钮,如果我点击菜单按钮,像添加,在那一个它会显示一个页面,在该页面我不得不添加数据,然后单击保存,它在列表视图来显示和帖子在网站上也

我怎么能做到这一点的。


解决方案

 公共无效POSTDATA(){
//创建一个新的HttpClient和邮政头
HttpClient的HttpClient的=新DefaultHttpClient();
HttpPost httppost =新
HttpPost(http://abcd.wxyz.com/);尝试{
     清单<&的NameValuePair GT; namevaluepairs中=新的ArrayList<&的NameValuePair GT;();
    nameValuePairs.add(新BasicNameValuePair(IDToken1,用户名));
    nameValuePairs.add(新BasicNameValuePair(IDToken2,密码));
    httppost.setEntity(新UrlEn codedFormEntity(namevaluepairs中));    //执行HTTP POST请求
    HTT presponse响应= httpclient.execute(httppost);    如果(响应!= NULL){      。INT状态code = response.getStatusLine()的getStatus code();       如果(状态code == HttpStatus.SC_OK){
        串strResponse = EntityUtils.toString(response.getEntity());      }
   } }赶上(ClientProtocolException E){
  // TODO自动生成catch块
  }赶上(IOException异常五){
    // TODO自动生成catch块
  }
 }

I have created an android apps using json for getting from ror website and displaying in listview,Right now i want to add the data from our apps,it has to display in listview in our apps also and then it has to show in website also.How to use post method and display in our apps.

to get method i used like that

public class MainActivity extends ListActivity implements FetchDataListener
{
    private ProgressDialog dialog;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.activity_list_item);
        initView();
    }

    private void initView()
    {
        // show progress dialog
        dialog = ProgressDialog.show(this, "", "Loading...");
        String url = "http://floating-wildwood-1154.herokuapp.com/posts.json";
        FetchDataTask task = new FetchDataTask(this);
        task.execute(url);
    }

    @Override
    public void onFetchComplete(List<Application> data)
    {
        // dismiss the progress dialog
        if ( dialog != null )
            dialog.dismiss();
        // create new adapter
        ApplicationAdapter adapter = new ApplicationAdapter(this, data);
        // set the adapter to list
        setListAdapter(adapter);
    }

    @Override
    public void onFetchFailure(String msg)
    {
        // dismiss the progress dialog
        if ( dialog != null )
            dialog.dismiss();
        // show failure message
        Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
    }
}

fetchdatatask.java

public class FetchDataTask extends AsyncTask<String, Void, String>
{
    private final FetchDataListener listener;
    private String msg;

    public FetchDataTask(FetchDataListener listener)
    {
        this.listener = listener;
    }

    @Override
    protected String doInBackground(String... params)
    {
        if ( params == null )
            return null;
        // get url from params
        String url = params[0];
        try
        {
            // create http connection
            HttpClient client = new DefaultHttpClient();
            HttpGet httpget = new HttpGet(url);
            // connect
            HttpResponse response = client.execute(httpget);
            // get response
            HttpEntity entity = response.getEntity();
            if ( entity == null )
            {
                msg = "No response from server";
                return null;
            }
            // get response content and convert it to json string
            InputStream is = entity.getContent();
            return streamToString(is);
        }
        catch ( IOException e )
        {
            msg = "No Network Connection";
        }
        return null;
    }

    @Override
    protected void onPostExecute(String sJson)
    {
        if ( sJson == null )
        {
            if ( listener != null )
                listener.onFetchFailure(msg);
            return;
        }
        try
        {
            // convert json string to json object
            JSONObject jsonObject = new JSONObject(sJson);
            JSONArray aJson = jsonObject.getJSONArray("post");
            // create apps list
            List<Application> apps = new ArrayList<Application>();
            for ( int i = 0; i < aJson.length(); i++ )
            {
                JSONObject json = aJson.getJSONObject(i);
                Application app = new Application();
                app.setContent(json.getString("content"));
                // add the app to apps list
                apps.add(app);
            }
            //notify the activity that fetch data has been complete
            if ( listener != null )
                listener.onFetchComplete(apps);
        }
        catch ( JSONException e )
        {
            e.printStackTrace();
            msg = "Invalid response";
            if ( listener != null )
                listener.onFetchFailure(msg);
            return;
        }
    }

    /**
     * This function will convert response stream into json string
     *
     * @param is
     *            respons string
     * @return json string
     * @throws IOException
     */
    public String streamToString(final InputStream is) throws IOException
    {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
        String line = null;
        try
        {
            while ( (line = reader.readLine()) != null )
            {
                sb.append(line + "\n");
            }
        }
        catch ( IOException e )
        {
            throw e;
        }
        finally
        {
            try
            {
                is.close();
            }
            catch ( IOException e )
            {
                throw e;
            }
        }
        return sb.toString();
    }
}

Like this i am using get method and displaying also,for same purpose i want to add the post method to displaying in android listview and shown in website also.

if i will create one button if i click the menu button like add,in that one it will shows one page,in that page i have to add the data and click save,it has to display in listview and post in website also

How i can do that one.

解决方案
          public void postData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new
HttpPost("http://abcd.wxyz.com/");

try {
     List <NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    nameValuePairs.add(new BasicNameValuePair("IDToken1", "username"));
    nameValuePairs.add(new BasicNameValuePair("IDToken2", "password"));


    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

    // Execute HTTP Post Request
    HttpResponse response = httpclient.execute(httppost);

    if(response != null) {

      int statuscode = response.getStatusLine().getStatusCode();

       if(statuscode==HttpStatus.SC_OK) {
        String strResponse = EntityUtils.toString(response.getEntity());

      }
   }

 } catch (ClientProtocolException e) {
  // TODO Auto-generated catch block
  } catch (IOException e) {
    // TODO Auto-generated catch block
  }
 }

这篇关于如何使用JSON使用POST方法在android系统的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 12:40