【问题标题】:How to use post method in android using json如何使用json在android中使用post方法
【发布时间】:2013-05-23 11:39:06
【问题描述】:

我创建了一个 android 应用程序,使用 json 从 ror 网站获取并显示在列表视图中,现在我想从我们的应用程序中添加数据,它也必须显示在我们应用程序的列表视图中,然后它必须显示在网站也是。如何在我们的应用程序中使用发布方法和显示。

获取我使用的方法

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();
    }
}

像这样我正在使用 get 方法并显示,出于同样的目的,我想将 post 方法添加到在 android listview 中显示并在网站中显示。

如果我在单击菜单按钮(如添加)时创建一个按钮,在该按钮中将显示一页,在该页面中我必须添加数据并单击保存,它必须在列表视图中显示和也可以在网站上发帖

我怎样才能做到这一点。

【问题讨论】:

    标签: java android json


    【解决方案1】:

    你可以使用HttpPost

        @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();
            HttpPost request = new HttpPost(url);
            try{
        StringEntity s = new StringEntity(json.toString()); //json is ur json object
        s.setContentEncoding("UTF-8");
        s.setContentType("application/json");
        request.setEntity(s);
        request.addHeader("Accept", "text/plain"); //give here your post method return type
    
        HttpResponse response = client.execute(request);
            // 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);
    

    【讨论】:

    • 这是发送数据到服务器的代码,你必须在你的服务器上编写可以接受json对象的post方法。
    • 实际上,如果我将在该按钮中提供菜单单击按钮,则会打开一个添加弹出窗口,如果我单击意味着它显示具有一个 edittexbox 并保存的新活动,从他们如何为服务器获取它和我们如何在列表视图中显示,我们可以保存在服务器或数据库中
    • 在保存按钮上写一个点击事件来从edittext中获取数据。您可以使用 myeditText.getText().toString() 从 edittext 检索数据; myeditText 是您的编辑文本名称。将此数据转换为 json 对象并调用您的异步任务
    • 你能看到那个链接吗,我可以在我的代码中使用那个链接吗,如何获取那个字符串并发布它
    • 我有一个疑问,如何获取数据并在 lisview 中显示,并将该数据转换为 json 对象 @Ashu
    【解决方案2】:

    您必须采取的主要步骤如下:

    在您的 Android 应用中添加代码以将数据发布到您的服务器。
    你可以在网上找到很多关于如何做到这一点的例子。这是一个例子: How to send POST request in JSON using HTTPClient?

    拥有可以处理您发送的 JSON 数据的网络服务。
    如何执行此操作取决于您使用的服务器端技术。

    更新与您的 ListView 关联的列表

    【讨论】:

    • ,这也是我想在服务器端做的吗
    【解决方案3】:
              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
      }
     }
    

    【讨论】:

    • 我必须在哪里添加这些代码,如何从列表视图中获取它,我要添加什么
    • 执行服务返回HttpResponse并将response转换为字符串后即可解析
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-12
    相关资源
    最近更新 更多