简体   繁体   English

从服务器接收响应时出错?

[英]Error receiving response from the server?

I'm making an app that stores some data on a database, then it retrieves it. 我正在制作一个将一些数据存储在数据库中,然后将其检索的应用程序。 On the server side I'm working with PHP, and on the client side I've got this file that gets the input and pass it to the PHP file. 在服务器端,我正在使用PHP,在客户端端,我已经获得了获取输入并将其传递给PHP文件的文件。

new AsyncTask<String, String, String>() {

                JSONParser jsonParser = new JSONParser();
                private ProgressBar pBar;
                private String url_post_pet = "http://192.168.0.13/Android/post_pet.php";

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

                /**
                 * Before starting background thread Show Progress Dialog
                 */
                @Override
                protected void onPreExecute() {
                    super.onPreExecute();
                    //pBar = new ProgressBar();
                    //pBar.setIndeterminate(false);
                    //pBar.setVisibility(View.VISIBLE);
                }

                @Override
                protected String doInBackground(String... args) {
                    // Building Parameters
                    HashMap<String, String> params = new HashMap<>();
                    params.put("name", a);
                    params.put("breed", BREED);
                    params.put("type", TYPE);
                    params.put("images", "Whatever");
                    params.put("description", c);
                    params.put("coords", b);

                    // getting JSON Object
                    // Note that create product url accepts POST method
                    JSONObject json = jsonParser.makeHttpRequest(url_post_pet,
                            "POST", params);
                    // check log cat for response
                    Log.d("Create Response", json.toString());

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

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

                            // closing this screen
                            finish();
                        } else {
                            // failed to create product
                        }
                    } catch (JSONException e) {
                        System.out.println("exception" + e);
                        e.printStackTrace();
                    }
                    System.out.println("nul");
                    return null;
                }

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

        }
    });
}

Also, i've got this JSONParser: 另外,我有这个JSONParser:

public class JSONParser {

String charset = "UTF-8";
HttpURLConnection conn;
DataOutputStream wr;
StringBuilder result;
URL urlObj;
JSONObject jObj = null;
StringBuilder sbParams;
String paramsString;

public JSONObject makeHttpRequest(String url, String method,
                                  HashMap<String, String> params) {

    sbParams = new StringBuilder();
    int i = 0;
    for (String key : params.keySet()) {
        try {
            if (i != 0){
                sbParams.append("&");
            }
            sbParams.append(key).append("=")
                    .append(URLEncoder.encode(params.get(key), charset));

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        i++;
    }

    if (method.equals("POST")) {
        // request method is POST
        try {
            urlObj = new URL(url);
            conn = (HttpURLConnection) urlObj.openConnection();
            conn.setDoOutput(true);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Accept-Charset", charset);
            conn.setReadTimeout(10000);
            conn.setConnectTimeout(15000);
            conn.connect();

            paramsString = sbParams.toString();

            wr = new DataOutputStream(conn.getOutputStream());
            wr.writeBytes(paramsString);
            wr.flush();
            wr.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    else if(method.equals("GET")){
        // request method is GET

        if (sbParams.length() != 0) {
            url += "?" + sbParams.toString();
        }

        try {
            urlObj = new URL(url);
            conn = (HttpURLConnection) urlObj.openConnection();
            conn.setDoOutput(false);
            conn.setRequestMethod("GET");
            conn.setRequestProperty("Accept-Charset", charset);
            conn.setConnectTimeout(15000);
            conn.connect();

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

    }

    try {
        //Receive the response from the server
        InputStream in = new BufferedInputStream(conn.getInputStream());
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        result = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            result.append(line);
        }

        Log.d("JSON Parser", "result: " + result.toString());
    } catch (IOException e) {
        e.printStackTrace();
    }

    conn.disconnect();

    // try parse the string to a JSON object
    try {
        System.out.println(jObj);
        jObj = new JSONObject(result.toString());
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON Object
    return jObj;
}

And this is the error i get every time i submit the data: 这是我每次提交数据时都会遇到的错误:

08-26 12:51:08.236 5089-5156/chtecnologies.myapplication D/JSON Parser: result:08-26 12:51:08.239 5089-5156/chtecnologies.myapplication E/JSON Parser: Error parsing data org.json.JSONException: End of input at character 0 of 08-26 12:51:08.793 5089-5096/chtecnologies.myapplication W/art: Suspending all threads took: 190.496ms 08-26 12:51:09.245 5089-5096/chtecnologies.myapplication W/art: Suspending all threads took: 137.277ms 08-26 12:51:09.267 5089-5156/chtecnologies.myapplication E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1 Process: chtecnologies.myapplication, PID: 5089 java.lang.RuntimeException: An error occured while executing doInBackground() at android.os.AsyncTask$3.done(AsyncTask.java:304) at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355) at java.util.concurrent.FutureTask.setException(FutureTask.java:222) at java.util.concurrent.FutureTask.run(FutureTask.java:242) at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231) at java.util.concurr 08-26 12:51:08.236 5089-5156 / chtecnologies.myapplication D / JSON解析器:结果:08-26 12:51:08.239 5089-5156 / chtecnologies.myapplication E / JSON解析器:解析数据org.json.JSONException时出错:输入结束于08-26 12:51:08.793 5089-5096 / chtecnologies.myapplication W的字符0:艺术:暂停所有线程占用:190.496ms 08-26 12:51:09.245 5089-5096 / chtecnologies.myapplication W / art:暂停所有线程:137.277ms 08-26 12:51:09.267 5089-5156 / chtecnologies.myapplication E / AndroidRuntime:致命例外:AsyncTask#1进程:chtecnologies.myapplication,PID:5089 java.lang.RuntimeException:在java.util.concurrent.FutureTask的java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)的android.os.AsyncTask $ 3.done(AsyncTask.java:304)上执行doInBackground()时发生错误。 setException(FutureTask.java:222)在java.util.concurrent.FutureTask.run(FutureTask.java:242)在android.os.AsyncTask $ SerialExecutor $ 1.run(AsyncTask.java:231)在java.util.concurr ent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) at java.lang.Thread.run(Thread.java:818) Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String org.json.JSONObject.toString()' on a null object reference at chtecnologies.myapplication.PostPet$4$1.doInBackground(PostPet.java:154) at chtecnologies.myapplication.PostPet$4$1.doInBackground(PostPet.java:118) at android.os.AsyncTask$2.call(AsyncTask.java:292) at java.util.concurrent.FutureTask.run(FutureTask.java:237) at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) at java.lang.Thread.run(Thread.java:818) ent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)at java.util.concurrent.ThreadPoolExecutor $ Worker.run(ThreadPoolExecutor.java:587)at java.lang.Thread.run(Thread.java:818)原因:java .lang.NullPointerException:尝试在chtecnologies.myapplication.PostPet $ 4 $ 1.doInBackground(PostPet.java:154)的chtecnologies.myapplication.PostPet上对空对象引用调用虚拟方法'java.lang.String org.json.JSONObject.toString()' .myapplication.PostPet $ 4 $ 1.doInBackground(PostPet.java:118)在android.os.AsyncTask $ 2.call(AsyncTask.java:292)在java.util.concurrent.FutureTask.run(FutureTask.java:237)在Android .os.AsyncTask $ SerialExecutor $ 1.run(AsyncTask.java:231)at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)at java.util.concurrent.ThreadPoolExecutor $ Worker.run(ThreadPoolExecutor.java: 587)在java.lang.Thread.run(Thread.java:818)

The data successfully goes into the database, but there seems to be a problem in the JSONParser, than can't get the result of the PHP file. 数据已成功进入数据库,但是JSONParser中似乎有一个问题,即无法获得PHP文件的结果。

Would you tell me if there's anything wrong in the JSONParser file or somewhere else? 您能告诉我JSONParser文件或其他地方有什么问题吗? This is the first time that i implement a server in my app, i hope you can help me! 这是我第一次在我的应用程序中实现服务器,希望您能为我提供帮助! Thanks 谢谢

The way you are sending data looks fishy. 您发送数据的方式看起来很糟糕。 If you want to send data in POST use HttpURLConnection like 如果要在POST中发送数据,请使用HttpURLConnection类的

String postParam = "name=" + a + "&breed=" + BREED + "&type=" + "&images=" +
        Whatever + "&description=" + c + "&coords=" + b;

try {
    URL url = new URL(url);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();

    connection.setRequestMethod("POST");
    connection.setDoOutput(true);
    connection.setDoInput(true);
    connection.setRequestProperty("Content-type", "application/x-www-form-urlencoded");

    OutputStream os = connection.getOutputStream();
    os.write(postParam.getBytes());
    os.flush();
    os.close();

    // Fetching the response code
    responseCode = connection.getResponseCode();
    Log.d(TAG, "POST Response Code: " + responseCode);
} catch (Exception e) {
    e.printStackTrace();
}

connection.setRequestMethod - sets Method you want to send your data with GET/POST connection.setRequestMethod-设置要使用GET / POST发送数据的方法

connection.setDoOutput(true) - to let you sent the output connection.setDoOutput(true) -让您发送输出

connection.setDoInput(true) - to let you receive input after sending the data (if any) connection.setDoInput(true) -让您在发送数据后接收输入(如果有)

Hope this solves your problem! 希望这能解决您的问题!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM