Android Json HttpGet / Post HttpResponse

时间:2013-12-14 18:43:08

标签: java php mysql json httpresponse

我正在尝试根据条形码编号从mysql数据库中获取产品。我检查了他们正在使用的PHP代码,但在android方面我犯了一个错误。 这是我的GetProductDetails类(我认为这部分没问题);

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

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
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;
import android.widget.Toast;

public class Query_product extends Activity {
EditText txtId, txtName, txtPrice, txtDesc;
Button btnSave, btnDelete;
String ID = "";
String pid;

// Progress Dialog
private ProgressDialog pDialog;


// Creating JSON Parser object
JSONParser jsonParser = new JSONParser();


// url to get all products list
private static final String url_product_details = "http://10.0.2.2/ssa/get_product_details.php";
private static final String url_update_product = "http://10.0.2.2/ssa/update_product.php";
private static final String url_delete_product = "http://10.0.2.2/ssa/delete_product.php";

// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCT = "product";
private static final String TAG_PID = "barcode";
private static final String TAG_NAME = "name";
private static final String TAG_PRICE = "price";
private static final String TAG_DESCRIPTION = "description";

// products JSONArray
JSONArray products = null;

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

    btnSave = (Button) findViewById(R.id.btnSave);
    btnDelete = (Button) findViewById(R.id.btnDelete);



    ID += " " + getIntent().getExtras().getString(Constants.ID);
    pid = ID;



    new GetProductDetails().execute();
    btnSave.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // starting background task to update product
            new SaveProductDetails().execute();
        }
    });

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

        @Override
        public void onClick(View arg0) {
            // deleting product in background thread
            new DeleteProduct().execute();
        }
    });
}

class GetProductDetails extends AsyncTask<String, String, String> {


    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(Query_product.this);
        pDialog.setMessage("Loading product details. Please wait...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    protected String doInBackground(String... params) {

        // updating UI from Background Thread
        runOnUiThread(new Runnable() {
            public void run() {
                // Check for success tag
                int success;
                try {
                    // Building Parameters
                    List<NameValuePair> params = new ArrayList<NameValuePair>();
                    params.add(new BasicNameValuePair(TAG_PID, pid));
                    // getting product details by making HTTP request
                    // Note that product details url will use GET request
                    JSONObject json = jsonParser.makeHttpRequest(
                            url_product_details, "GET", params);
                    // check your log for json response
                    Log.d("Single Product Details", json.toString());

                    // json success tag
                    success = json.getInt(TAG_SUCCESS);
                    if (success == 1) {
                        // successfully received product details
                        JSONArray productObj = json
                                .getJSONArray(TAG_PRODUCT); // JSON Array

                        // get first product object from JSON Array
                        JSONObject product = productObj.getJSONObject(0);

                        // product with this pid found
                        // Edit Text
                        txtId = (EditText) findViewById(R.id.inputId);
                        txtName = (EditText) findViewById(R.id.inputName);
                        txtPrice = (EditText) findViewById(R.id.inputPrice);
                        txtDesc = (EditText) findViewById(R.id.inputDesc);

                        // display product data in EditText
                        txtId.setText(product.getString(TAG_PID));
                        txtName.setText(product.getString(TAG_NAME));
                        txtPrice.setText(product.getString(TAG_PRICE));
                        txtDesc.setText(product.getString(TAG_DESCRIPTION));

                    }
                    else
                    {

                        String error = "Not found!";
                        Toast.makeText(Query_product.this, error, Toast.LENGTH_LONG).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });

        return null;
    }

这里是makeHttpRequest类;

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

        }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");
        }
        is.close();
        json = sb.toString();
    } catch (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.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON String
    return jObj;

}
}

我无法解决问题。程序一直运行到这一行;

HttpResponse httpResponse = httpClient.execute(httpGet);

Logcat错误;

  

12-14 18:05:30.994:E / AndroidRuntime(986):致命异常:主要   12-14 18:05:30.994:E / AndroidRuntime(986):android.os.NetworkOnMainThreadException   12-14 18:05:30.994:E / AndroidRuntime(986):在android.os.StrictMode $ AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)   12-14 18:05:30.994:E / AndroidRuntime(986):at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)   12-14 18:05:30.994:E / AndroidRuntime(986):at libcore.io.IoBridge.connectErrno(IoBridge.java:127)   12-14 18:05:30.994:E / AndroidRuntime(986):at libcore.io.IoBridge.connect(IoBridge.java:112)   12-14 18:05:30.994:E / AndroidRuntime(986):at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)   12-14 18:05:30.994:E / AndroidRuntime(986):at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)   12-14 18:05:30.994:E / AndroidRuntime(986):at java.net.Socket.connect(Socket.java:842)   12-14 18:05:30.994:E / AndroidRuntime(986):at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)   12-14 18:05:30.994:E / AndroidRuntime(986):at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144)   12-14 18:05:30.994:E / AndroidRuntime(986):at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)   12-14 18:05:30.994:E / AndroidRuntime(986):at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)   12-14 18:05:30.994:E / AndroidRuntime(986):at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)   12-14 18:05:30.994:E / AndroidRuntime(986):at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)   12-14 18:05:30.994:E / AndroidRuntime(986):at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)   12-14 18:05:30.994:E / AndroidRuntime(986):at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)   12-14 18:05:30.994:E / AndroidRuntime(986):at com.example.ssa.JSONParser.makeHttpRequest(JSONParser.java:66)   12-14 18:05:30.994:E / AndroidRuntime(986):at com.example.ssa.Query_product $ GetProductDetails $ 1.run(Query_product.java:134)   12-14 18:05:30.994:E / AndroidRuntime(986):在android.os.Handler.handleCallback(Handler.java:725)   12-14 18:05:30.994:E / AndroidRuntime(986):在android.os.Handler.dispatchMessage(Handler.java:92)   12-14 18:05:30.994:E / AndroidRuntime(986):在android.os.Looper.loop(Looper.java:137)   12-14 18:05:30.994:E / AndroidRuntime(986):在android.app.ActivityThread.main(ActivityThread.java:5041)   12-14 18:05:30.994:E / AndroidRuntime(986):at java.lang.reflect.Method.invokeNative(Native Method)   12-14 18:05:30.994:E / AndroidRuntime(986):at java.lang.reflect.Method.invoke(Method.java:511)   12-14 18:05:30.994:E / AndroidRuntime(986):at com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:793)   12-14 18:05:30.994:E / AndroidRuntime(986):at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)   12-14 18:05:30.994:E / AndroidRuntime(986):at dalvik.system.NativeStart.main(Native Method)   12-14 18:10:3​​1.483:I / Process(986):发送信号。 PID:986 SIG:9   12-14 18:10:3​​3.372:D / gralloc_goldfish(1025):未检测到GPU仿真的仿真器。

3 个答案:

答案 0 :(得分:3)

您无法在主线程上执行网络任务,因为如果网络任务需要很长时间,它可能会阻止您的应用程序。您需要使用AsyncTask在后​​台运行此类任务。

这是documentation

答案 1 :(得分:1)

尝试在setContentView()下方的主要活动中使用以下代码,以避免networkOnmainThread例外..

if (android.os.Build.VERSION.SDK_INT > 9) {
                StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
                StrictMode.setThreadPolicy(policy);
            }

答案 2 :(得分:0)

看起来错误不是json。 您正试图从主线程中调用一个不允许从android 4.0中获取的URL 尝试使用AsynTask或从辅助线程调用url。