org.apache.http.conn.HttpHostConnectException:拒绝连接到http://127.0.0.1

时间:2014-03-26 12:04:00

标签: php android mysql

我有一个问题:我想在模拟器上通过php显示来自mysql数据库的数据,我发现异常

Connection to 127.0.0.1 refused

我将127.0.0.1更改为localhost10.0.2.110.0.2.2它是相同的。 我使用 EasyPhp ,我已经多次重置我的电脑和服务器,但它是一样的。 当我在浏览器上执行链接时,它可以正常工作。

AllProductsActivity

package com.example.androidhive;

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

import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ListActivity;
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.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class AllProductsActivity extends ListActivity {

    // Progress Dialog
    private ProgressDialog pDialog;

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

    ArrayList<HashMap<String, String>> productsList;

    // url to get all products list
    private static String url_all_products = "http://127.0.0.1/android_connect/get_all_products.php";

    // JSON Node names
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_PRODUCTS = "products";
    private static final String TAG_PID = "pid";
    private static final String TAG_NAME = "name";

    // products JSONArray
    JSONArray products = null;

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

        // Hashmap for ListView
        productsList = new ArrayList<HashMap<String, String>>();

        // Loading products in Background Thread
        new LoadAllProducts().execute();

        // Get listview
        ListView lv = getListView();

        // on seleting single product
        // launching Edit Product Screen
        lv.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                // getting values from selected ListItem
                String pid = ((TextView) view.findViewById(R.id.pid)).getText()
                        .toString();

                // Starting new intent
                Intent in = new Intent(getApplicationContext(),
                        EditProductActivity.class);
                // sending pid to next activity
                in.putExtra(TAG_PID, pid);

                // starting new activity and expecting some response back
                startActivityForResult(in, 100);
            }
        });

    }

    // Response from Edit Product Activity
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // if result code 100
        if (resultCode == 100) {
            // if result code 100 is received 
            // means user edited/deleted product
            // reload this screen again
            Intent intent = getIntent();
            finish();
            startActivity(intent);
        }

    }

    /**
     * Background Async Task to Load all product by making HTTP Request
     * */
    class LoadAllProducts extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(AllProductsActivity.this);
            pDialog.setMessage("Loading products. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        /**
         * getting All products from url
         * */
        protected String doInBackground(String... args) {
            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            // getting JSON string from URL
            JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);

            // Check your log cat for JSON reponse
            Log.d("All Products: ", json.toString());

            try {
                // Checking for SUCCESS TAG
                int success = json.getInt(TAG_SUCCESS);

                if (success == 1) {
                    // products found
                    // Getting Array of Products
                    products = json.getJSONArray(TAG_PRODUCTS);

                    // looping through All Products
                    for (int i = 0; i < products.length(); i++) {
                        JSONObject c = products.getJSONObject(i);

                        // Storing each json item in variable
                        String id = c.getString(TAG_PID);
                        String name = c.getString(TAG_NAME);

                        // creating new HashMap
                        HashMap<String, String> map = new HashMap<String, String>();

                        // adding each child node to HashMap key => value
                        map.put(TAG_PID, id);
                        map.put(TAG_NAME, name);

                        // adding HashList to ArrayList
                        productsList.add(map);
                    }
                } else {
                    // no products found
                    // Launch Add New product Activity
                    Intent i = new Intent(getApplicationContext(),
                            NewProductActivity.class);
                    // Closing all previous activities
                    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(i);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog after getting all products
            pDialog.dismiss();
            // updating UI from Background Thread
            runOnUiThread(new Runnable() {
                public void run() {
                    /**
                     * Updating parsed JSON data into ListView
                     * */
                    ListAdapter adapter = new SimpleAdapter(
                            AllProductsActivity.this, productsList,
                            R.layout.list_item, new String[] { TAG_PID,
                                    TAG_NAME},
                            new int[] { R.id.pid, R.id.name });
                    // updating listview
                    setListAdapter(adapter);
                }
            });

        }

    }
}

JSONParser

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

            }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"), 10);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            Log.e("Buffer Error", "getting JSon String from server :-- " + sb.toString());
            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;

    }
}

堆栈跟踪?

03-26 00:21:10.348: W/System.err(334): org.apache.http.conn.HttpHostConnectException: Connection to http://127.0.0.1:1080 refused
03-26 00:21:10.358: W/System.err(334):  at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:178)
03-26 00:21:10.358: W/System.err(334):  at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
03-26 00:21:10.358: W/System.err(334):  at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
03-26 00:21:10.358: W/System.err(334):  at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:348)
03-26 00:21:10.379: W/System.err(334):  at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
03-26 00:21:10.379: W/System.err(334):  at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
03-26 00:21:10.389: W/System.err(334):  at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
03-26 00:21:10.389: W/System.err(334):  at com.example.androidhive.JSONParser.makeHttpRequest(JSONParser.java:62)
03-26 00:21:10.389: W/System.err(334):  at com.example.androidhive.AllProductsActivity$LoadAllProducts.doInBackground(AllProductsActivity.java:128)
03-26 00:21:10.389: W/System.err(334):  at com.example.androidhive.AllProductsActivity$LoadAllProducts.doInBackground(AllProductsActivity.java:1)
03-26 00:21:10.389: W/System.err(334):  at android.os.AsyncTask$2.call(AsyncTask.java:185)
03-26 00:21:10.429: W/System.err(334):  at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
03-26 00:21:10.451: W/System.err(334):  at java.util.concurrent.FutureTask.run(FutureTask.java:137)
03-26 00:21:10.458: W/System.err(334):  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1068)
03-26 00:21:10.471: W/System.err(334):  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:561)
03-26 00:21:10.471: W/System.err(334):  at java.lang.Thread.run(Thread.java:1096)
03-26 00:21:10.478: W/System.err(334): Caused by: java.net.ConnectException: /127.0.0.1:1080 - Connection refused
03-26 00:21:10.488: W/System.err(334):  at org.apache.harmony.luni.net.PlainSocketImpl.connect(PlainSocketImpl.java:254)
03-26 00:21:10.488: W/System.err(334):  at org.apache.harmony.luni.net.PlainSocketImpl.connect(PlainSocketImpl.java:533)
03-26 00:21:10.488: W/System.err(334):  at java.net.Socket.connect(Socket.java:1055)
03-26 00:21:10.488: W/System.err(334):  at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
03-26 00:21:10.498: W/System.err(334):  at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:143)
03-26 00:21:10.498: W/System.err(334):  ... 15 more
03-26 00:21:10.528: E/Buffer Error(334): Error converting result java.lang.NullPointerException
03-26 00:21:10.548: E/JSON Parser(334): Error parsing data org.json.JSONException: End of input at character 0 of 
03-26 00:21:10.578: W/dalvikvm(334): threadid=7: thread exiting with uncaught exception (group=0x4001d800)
03-26 00:21:10.659: E/AndroidRuntime(334): FATAL EXCEPTION: AsyncTask #1
03-26 00:21:10.659: E/AndroidRuntime(334): java.lang.RuntimeException: An error occured while executing doInBackground()
03-26 00:21:10.659: E/AndroidRuntime(334):  at android.os.AsyncTask$3.done(AsyncTask.java:200)
03-26 00:21:10.659: E/AndroidRuntime(334):  at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
03-26 00:21:10.659: E/AndroidRuntime(334):  at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
03-26 00:21:10.659: E/AndroidRuntime(334):  at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
03-26 00:21:10.659: E/AndroidRuntime(334):  at java.util.concurrent.FutureTask.run(FutureTask.java:137)
03-26 00:21:10.659: E/AndroidRuntime(334):  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1068)
03-26 00:21:10.659: E/AndroidRuntime(334):  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:561)
03-26 00:21:10.659: E/AndroidRuntime(334):  at java.lang.Thread.run(Thread.java:1096)
03-26 00:21:10.659: E/AndroidRuntime(334): Caused by: java.lang.NullPointerException
03-26 00:21:10.659: E/AndroidRuntime(334):  at com.example.androidhive.AllProductsActivity$LoadAllProducts.doInBackground(AllProductsActivity.java:131)
03-26 00:21:10.659: E/AndroidRuntime(334):  at com.example.androidhive.AllProductsActivity$LoadAllProducts.doInBackground(AllProductsActivity.java:1)
03-26 00:21:10.659: E/AndroidRuntime(334):  at android.os.AsyncTask$2.call(AsyncTask.java:185)
03-26 00:21:10.659: E/AndroidRuntime(334):  at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
03-26 00:21:10.659: E/AndroidRuntime(334):  ... 4 more
03-26 00:21:12.128: E/WindowManager(334): Activity com.example.androidhive.AllProductsActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@43e50508 that was originally added here
03-26 00:21:12.128: E/WindowManager(334): android.view.WindowLeaked: Activity com.example.androidhive.AllProductsActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@43e50508 that was originally added here
03-26 00:21:12.128: E/WindowManager(334):   at android.view.ViewRoot.<init>(ViewRoot.java:247)
03-26 00:21:12.128: E/WindowManager(334):   at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:148)
03-26 00:21:12.128: E/WindowManager(334):   at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
03-26 00:21:12.128: E/WindowManager(334):   at android.view.Window$LocalWindowManager.addView(Window.java:424)
03-26 00:21:12.128: E/WindowManager(334):   at android.app.Dialog.show(Dialog.java:241)
03-26 00:21:12.128: E/WindowManager(334):   at com.example.androidhive.AllProductsActivity$LoadAllProducts.onPreExecute(AllProductsActivity.java:118)
03-26 00:21:12.128: E/WindowManager(334):   at android.os.AsyncTask.execute(AsyncTask.java:391)
03-26 00:21:12.128: E/WindowManager(334):   at com.example.androidhive.AllProductsActivity.onCreate(AllProductsActivity.java:58)
03-26 00:21:12.128: E/WindowManager(334):   at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
03-26 00:21:12.128: E/WindowManager(334):   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
03-26 00:21:12.128: E/WindowManager(334):   at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
03-26 00:21:12.128: E/WindowManager(334):   at android.app.ActivityThread.access$2300(ActivityThread.java:125)
03-26 00:21:12.128: E/WindowManager(334):   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
03-26 00:21:12.128: E/WindowManager(334):   at android.os.Handler.dispatchMessage(Handler.java:99)
03-26 00:21:12.128: E/WindowManager(334):   at android.os.Looper.loop(Looper.java:123)
03-26 00:21:12.128: E/WindowManager(334):   at android.app.ActivityThread.main(ActivityThread.java:4627)
03-26 00:21:12.128: E/WindowManager(334):   at java.lang.reflect.Method.invokeNative(Native Method)
03-26 00:21:12.128: E/WindowManager(334):   at java.lang.reflect.Method.invoke(Method.java:521)
03-26 00:21:12.128: E/WindowManager(334):   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
03-26 00:21:12.128: E/WindowManager(334):   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
03-26 00:21:12.128: E/WindowManager(334):   at dalvik.system.NativeStart.main(Native Method)
03-26 00:21:16.099: I/Process(334): Sending signal. PID: 334 SIG: 9

2 个答案:

答案 0 :(得分:5)

如果您在设备中使用127.0.0.1,则它指向设备中的localhost。您必须使用服务器的IP。

祝你好运

答案 1 :(得分:0)

模拟器是另一台机器。

找到您的计算机的IP并使用它代替127.0.0.1