android中的JSON POST方法

时间:2014-05-24 08:56:08

标签: android json

我正在尝试创建一个phpmyadmin数据库,其中包含产品名称,价格和简短说明。我为JSON创建了一个单独的类,并且请求从源文件是android活动的另一个文件传输。但是在textview中输入值后,将出现进度对话框,然后关闭活动力。在logcat中,我可以看到我在textview中输入的值可供JSONParser.java类使用。这是JSONParser.java文件。

为了调试目的,我在logcat中打印json字符串。但它显示JSON字符串是br /(在开头和结尾有两个尖括号),表明它是换行符标签,显然这不能解析为JSON字符串,我认为这是强制关闭的原因。提前致谢。过去两天我一直坚持这一点。

package com.example.androidhive;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONParser
{
    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

// constructor
public JSONParser()
{

}

// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method, List<NameValuePair> params)
{

    // Making HTTP request
    try
    {
        // check for request method
        if (method == "POST")
        {
            // request method is POST
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();

            HttpPost httpPost = new HttpPost(url);

            httpPost.setEntity(new UrlEncodedFormEntity(params));

            HttpResponse httpResponse = httpClient.execute(httpPost);

            HttpEntity httpEntity = httpResponse.getEntity();

            is = httpEntity.getContent();

            Log.i("JSONPArser.java", "is.toString() = " + is.toString());
            Log.i("JSONPArser.java", "params.size = " + params.size());
            Log.i("JSONPArser.java", "params.get(0) = " + params.get(0));
            Log.i("JSONPArser.java", "params.get(1) = " + params.get(1));
            Log.i("JSONPArser.java", "params.get(2) = " + params.get(2));
        }
        else if (method == "GET")
        {
            // request method is GET
            DefaultHttpClient httpClient = new DefaultHttpClient();
            String paramString = URLEncodedUtils.format(params, "utf-8");
            url += "?" + paramString;
            HttpGet httpGet = new HttpGet(url);

            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();
        }

    }
    catch (UnsupportedEncodingException e)
    {
        e.printStackTrace();
    }
    catch (ClientProtocolException e)
    {
        e.printStackTrace();
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }

    try
    {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);

        StringBuilder sb = new StringBuilder();

        String line = null;

        while ((line = reader.readLine()) != null)
        {
            sb.append(line + "\n");

            Log.i("JSONPArser.java", "sb string append = " + sb.toString());
        }
        is.close();

        json = sb.toString();

        Log.i("JSONPArser.java", "json string = " + json);

    }
    catch (Exception e)
    {
        Log.i("JSONPArser.java", "Exception e");
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // try parse the string to a JSON object
    try
    {
        jObj = new JSONObject(json);
    }
    catch (JSONException e)
    {
        Log.i("JSONPArser.java", "JSONException e");
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON String
    return jObj;
    }
}

这是NewProductActivity.java文件。它是android活动的源文件。

package com.example.androidhive;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class NewProductActivity extends Activity
{

// Progress Dialog
private ProgressDialog pDialog;

JSONParser jsonParser = new JSONParser();
EditText inputName;
EditText inputPrice;
EditText inputDesc;

// url to create new product
private static String url_create_product = "http://192.168.199.80/android_connect/create_product.php";

// JSON Node names
private static final String TAG_SUCCESS = "success";

@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.add_product);

    // Edit Text
    inputName = (EditText) findViewById(R.id.inputName);
    inputPrice = (EditText) findViewById(R.id.inputPrice);
    inputDesc = (EditText) findViewById(R.id.inputDesc);

    // Create button
    Button btnCreateProduct = (Button) findViewById(R.id.btnCreateProduct);

    // button click event
    btnCreateProduct.setOnClickListener(new View.OnClickListener()
    {

        @Override
        public void onClick(View view)
        {
            // creating new product in background thread
            new CreateNewProduct().execute();
        }
    });
}

/**
 * Background Async Task to Create new product
 * */
class CreateNewProduct extends AsyncTask<String, String, String>
{

    /**
     * Before starting background thread Show Progress Dialog
     * */
    @Override
    protected void onPreExecute()
    {
        super.onPreExecute();
        pDialog = new ProgressDialog(NewProductActivity.this);
        pDialog.setMessage("Creating Product..");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    /**
     * Creating product
     * */
    protected String doInBackground(String... args)
    {
        String name = inputName.getText().toString();
        String price = inputPrice.getText().toString();
        String description = inputDesc.getText().toString();

        Log.i("NewProductActivity.java", "name = " + name);
        Log.i("NewProductActivity.java", "price = " + price);
        Log.i("NewProductActivity.java", "description = " + description);

        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("name", name));
        params.add(new BasicNameValuePair("price", price));
        params.add(new BasicNameValuePair("description", description));

        // getting JSON Object
        // Note that create product url accepts POST method
        JSONObject json = jsonParser.makeHttpRequest(url_create_product, "POST", params);

        // check log cat fro response
        //Log.i("NewProductActivity.java", json.toString());

        // check for success tag
        try
        {
            int success = json.getInt(TAG_SUCCESS);

            if (success == 1)
            {
                // successfully created product
                Intent i = new Intent(getApplicationContext(), AllProductsActivity.class);
                startActivity(i);

                // closing this screen
                finish();
            }
            else
            {
                // failed to create product
            }
        }
        catch (JSONException e)
        {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * After completing background task Dismiss the progress dialog
     * **/
    protected void onPostExecute(String file_url)
    {
        // dismiss the dialog once done
        pDialog.dismiss();
    }

    }
}

这是相应的布局文件。 addproduct.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<!-- Name Label -->

<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:paddingLeft="10dip"
    android:paddingRight="10dip"
    android:paddingTop="10dip"
    android:text="Product Name"
    android:textSize="17dip" />

<!-- Input Name -->

<EditText
    android:id="@+id/inputName"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_margin="5dip"
    android:layout_marginBottom="15dip"
    android:singleLine="true" />

<!-- Price Label -->

<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:paddingLeft="10dip"
    android:paddingRight="10dip"
    android:paddingTop="10dip"
    android:text="Price"
    android:textSize="17dip" />

<!-- Input Price -->

<EditText
    android:id="@+id/inputPrice"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_margin="5dip"
    android:layout_marginBottom="15dip"
    android:inputType="numberDecimal"
    android:singleLine="true" />

<!-- Description Label -->

<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:paddingLeft="10dip"
    android:paddingRight="10dip"
    android:paddingTop="10dip"
    android:text="Description"
    android:textSize="17dip" />

<!-- Input description -->

<EditText
    android:id="@+id/inputDesc"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_margin="5dip"
    android:layout_marginBottom="15dip"
    android:gravity="top"
    android:lines="4" />

<!-- Button Create Product -->

<Button
    android:id="@+id/btnCreateProduct"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Create Product" />

0 个答案:

没有答案