当前位置: 首页 > 知识库问答 >
问题:

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

罗法
2023-03-14

我在做一个应用程序,把一些数据存储在数据库中,然后它再检索它。在服务器端,我使用的是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();

        }
    });
}

另外,我有这个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;
}

共有1个答案

夏侯朝斑
2023-03-14

你发送数据的方式看起来很可疑。如果要使用HTTPURLConnection在POST中发送数据,请如下所示

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-设置要用GET/POST发送数据的方法

connection.setdoOutput(true)-让您发送输出

希望这能解决你的问题!

 类似资料:
  • 有人知道netty服务器处理程序取消从web服务器接收数据的最佳方法吗?我有一个服务器处理程序,它将HttpRequests代理到web服务器。但是,当请求客户端取消请求时,我希望在不关闭服务器处理程序和web服务器之间的连接的情况下停止从web服务器接收服务器通道上的数据。 有谁知道我怎么才能做到这一点。你的答复将不胜感激。 非常感谢。

  • 我写了一个JAVA代码,使用Apache Commons Net FTPClient遍历FTP位置,并在Excel文件中获得输出。 我正在使用commons-net-3.0.1。罐子我做了一些测试 并发送,但仍会收到相同的错误。 我要做的就是遍历一个目录,如果找到了文件,就在excel中获取文件名和文件更新日期,如果找到了目录,就进入目录,直到再次找到文件。 请帮助并询问是否需要任何其他信息。我是

  • HTTP/1.1 200确定缓存-控制:max-age=0,必须重新验证 内容-处置:附件;filename=“执行摘要.pdf” 内容-类型:application/pdf

  • 我有一个要求,其中,作为Web服务[Java]的一部分,我将作业的详细信息输入数据库,数据库由Windows服务[C#]异步处理,并对Javaweb服务通知作业的状态。 情景: 客户端对JavaWeb服务进行同步Restful调用。 JavaWeb Service将作业详细信息输入数据库(类似于进行异步调用),并等待Windows Service的响应(这是对JavaWeb Service的新HT

  • 我在Laravel项目中使用React js作为前端。从控制器,我将数组传递到我的视图: 现在在视图中,可以像这样循环数组: 这工作得很好。但是我想让视图更动态(顺便说一下,这是购物车中的产品列表)。例如,默认情况下,所有复选框都将被选中,这意味着用户正在购买所有商品。我希望如果用户取消选中一个框,总价格会发生变化。所以我做了一个React组件,并通过props将$项目数组传递给该组件: 还有一个

  • 客户端-NAT后面的Windows桌面,运行UDP客户端应用程序。 服务器-具有公共IP的Ubuntu服务器,运行一个UDP服务器应用程序,该应用程序期望在端口6000上发送数据包。 ClientPrivate/Public-客户端的私有/公共IP 服务器私有/公共 - 服务器的私有/公共 IP 客户端打开一个UDP套接字Client私人: 777和发送数据报Server公共: 6000 服务器从