将Android平板电脑连接到Web服务

时间:2012-12-21 13:16:55

标签: php android web-services wamp

我正在尝试将平板电脑连接到我的WAMP服务器中的Web服务。我已经尝试过做我读过的所有内容并且没有运气连接它。 Web服务从SQL Server读取数据并在应用程序中显示它。就目前而言,这就是它需要做的一切。我有一个代码,我从教程中遵循,以便我可以执行ASync任务,但它仍然没有帮助。这是代码:

package com.example.secondtestsqlserver;

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.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;

public class MainActivity extends Activity {
    private ProgressDialog pDialog;
    JSONParser jsonParser = new JSONParser();
    String pid;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
        .detectAll()
        .penaltyLog()
        .penaltyDialog()
        .build());
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

    public void clickSend(View view) {
        new TestWS().execute();
    }
    class TestWS extends AsyncTask<String, String, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(MainActivity.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("pid", pid));

                        // getting product details by making HTTP request
                        // Note that product details url will use GET request
                        JSONObject json = jsonParser.makeHttpRequest(
                                "http://170.54.162.239:80/webservice.php", "GET", params);

                        // check your log for json response
                        Log.d("Single Record Details", json.toString());

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

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

                            // product with this pid found
                            // Edit Text
                            EditText txtName = (EditText) findViewById(R.id.txtName);
                            EditText txtPrice = (EditText) findViewById(R.id.txtTest);

                            // display product data in EditText
                            txtName.setText(product.getString("test"));
                            txtPrice.setText(product.getString("name"));
//                            Log.e("Checking", product.getString("test"));
//                            Log.e("Checking", product.getString("name"));
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });

            return null;
        }
        protected void onPostExecute(String file_url) {
            // dismiss the dialog once got all details
            pDialog.dismiss();
        }
    }
}

这是JSONParser类

package com.example.secondtestsqlserver;

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 method
    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) {
            Log.e("Unsupported Encoding", Log.getStackTraceString(e));
        } catch (ClientProtocolException e) {
            Log.e("Client Protocol", Log.getStackTraceString(e));
        } catch (IOException e) {
            Log.e("IO Exception", Log.getStackTraceString(e));
        }

        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());
            System.out.println(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());
            Log.e("JSON Parser", json);
        }

        // return JSON String
        return jObj;

    }
}

这是PHP Web服务

<?php
    $serverName = "localhost\SQLExpress";
    $connectionOptions = array("Database"=>"Android");
    $conn = sqlsrv_connect($serverName, $connectionOptions);

/*  if ($conn)
    {
        echo "Connection established.<br />";
    }
    else
    {
        echo "Connection could not be established.<br />";
        die(print_r(sqlsrv_errors(), true));
    }*/

    $query = "SELECT * FROM AndroidTest;";

    $result = sqlsrv_query($conn, $query, array(), array("Scrollable" => SQLSRV_CURSOR_KEYSET));
    $master = array();
    if (sqlsrv_num_rows($result)) {
        $master["record"] = array();
        while ($posts = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC)) {
            $record = array();
            $record["test"] = $posts["test"];
            $record["name"] = $posts["name"];

            array_push($master["record"], $record);
        }
        $master["success"] = 1;
    }
    else {
        $master["success"] = 0;
        $master["message"] = "No products found";
    }
    header('Content-trype: application/json');
    echo json_encode($master);
    sqlsrv_close($conn);
?>

我确实知道PHP是对的,因为它给了我想要的数据,但是应用程序在我的平板电脑中不起作用,也不能在模拟器中工作。另请注意,在MainActivity类中,我使用StrictMode.setThreadPolicy()。这是因为我读到了当我得到onNetworkMainThreadException时,这通常可以解决问题,即使它不安全。当我找到无法连接的原因后,我当然打算改变它。错误就是这个:

12-21 09:03:45.049: E/IO Exception(25431): org.apache.http.conn.HttpHostConnectException: Connection to http://170.54.162.239:80 refused
12-21 09:03:45.049: E/IO Exception(25431):  at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:183)
12-21 09:03:45.049: E/IO Exception(25431):  at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
12-21 09:03:45.049: E/IO Exception(25431):  at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
12-21 09:03:45.049: E/IO Exception(25431):  at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
12-21 09:03:45.049: E/IO Exception(25431):  at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
12-21 09:03:45.049: E/IO Exception(25431):  at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
12-21 09:03:45.049: E/IO Exception(25431):  at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
12-21 09:03:45.049: E/IO Exception(25431):  at com.example.secondtestsqlserver.JSONParser.makeHttpRequest(JSONParser.java:62)
12-21 09:03:45.049: E/IO Exception(25431):  at com.example.secondtestsqlserver.MainActivity$TestWS$1.run(MainActivity.java:75)
12-21 09:03:45.049: E/IO Exception(25431):  at android.os.Handler.handleCallback(Handler.java:615)
12-21 09:03:45.049: E/IO Exception(25431):  at android.os.Handler.dispatchMessage(Handler.java:92)
12-21 09:03:45.049: E/IO Exception(25431):  at android.os.Looper.loop(Looper.java:137)
12-21 09:03:45.049: E/IO Exception(25431):  at android.app.ActivityThread.main(ActivityThread.java:4745)
12-21 09:03:45.049: E/IO Exception(25431):  at java.lang.reflect.Method.invokeNative(Native Method)
12-21 09:03:45.049: E/IO Exception(25431):  at java.lang.reflect.Method.invoke(Method.java:511)
12-21 09:03:45.049: E/IO Exception(25431):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
12-21 09:03:45.049: E/IO Exception(25431):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
12-21 09:03:45.049: E/IO Exception(25431):  at dalvik.system.NativeStart.main(Native Method)
12-21 09:03:45.049: E/IO Exception(25431): Caused by: java.net.ConnectException: failed to connect to /170.54.162.239 (port 80): connect failed: ENETUNREACH (Network is unreachable)
12-21 09:03:45.049: E/IO Exception(25431):  at libcore.io.IoBridge.connect(IoBridge.java:114)
12-21 09:03:45.049: E/IO Exception(25431):  at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
12-21 09:03:45.049: E/IO Exception(25431):  at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
12-21 09:03:45.049: E/IO Exception(25431):  at java.net.Socket.connect(Socket.java:842)
12-21 09:03:45.049: E/IO Exception(25431):  at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
12-21 09:03:45.049: E/IO Exception(25431):  at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144)
12-21 09:03:45.049: E/IO Exception(25431):  ... 17 more
12-21 09:03:45.049: E/IO Exception(25431): Caused by: libcore.io.ErrnoException: connect failed: ENETUNREACH (Network is unreachable)
12-21 09:03:45.049: E/IO Exception(25431):  at libcore.io.Posix.connect(Native Method)
12-21 09:03:45.049: E/IO Exception(25431):  at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:85)
12-21 09:03:45.049: E/IO Exception(25431):  at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
12-21 09:03:45.049: E/IO Exception(25431):  at libcore.io.IoBridge.connect(IoBridge.java:112)
12-21 09:03:45.049: E/IO Exception(25431):  ... 22 more
12-21 09:03:45.049: E/Buffer Error(25431): Error converting result java.lang.NullPointerException
12-21 09:03:45.049: E/JSON Parser(25431): Error parsing data org.json.JSONException: End of input at character 0 of 
12-21 09:03:45.049: E/AndroidRuntime(25431): FATAL EXCEPTION: main
12-21 09:03:45.049: E/AndroidRuntime(25431): java.lang.NullPointerException
12-21 09:03:45.049: E/AndroidRuntime(25431):    at com.example.secondtestsqlserver.MainActivity$TestWS$1.run(MainActivity.java:79)
12-21 09:03:45.049: E/AndroidRuntime(25431):    at android.os.Handler.handleCallback(Handler.java:615)
12-21 09:03:45.049: E/AndroidRuntime(25431):    at android.os.Handler.dispatchMessage(Handler.java:92)
12-21 09:03:45.049: E/AndroidRuntime(25431):    at android.os.Looper.loop(Looper.java:137)
12-21 09:03:45.049: E/AndroidRuntime(25431):    at android.app.ActivityThread.main(ActivityThread.java:4745)
12-21 09:03:45.049: E/AndroidRuntime(25431):    at java.lang.reflect.Method.invokeNative(Native Method)
12-21 09:03:45.049: E/AndroidRuntime(25431):    at java.lang.reflect.Method.invoke(Method.java:511)
12-21 09:03:45.049: E/AndroidRuntime(25431):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
12-21 09:03:45.049: E/AndroidRuntime(25431):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
12-21 09:03:45.049: E/AndroidRuntime(25431):    at dalvik.system.NativeStart.main(Native Method)

我不会问我是否还没有尝试过我在这里找到的所有内容以及我在互联网上找到的所有内容。我需要尽快完成这项工作,所以请您给我的任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:2)

这似乎是根本原因:

failed to connect to /170.54.162.239 (port 80): connect failed: ENETUNREACH (Network is unreachable)

因此,请确保您的服务正在那里运行,并且可以通过平板电脑访问。 (也许尝试从服务器获取HTML页面以确保您具有连接性)