有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java HttpURLConnection发布问题

我的程序中有以下代码,用于插入记录-

private Void downloadUrl() throws IOException {
        String postParameters;
        HttpURLConnection urlConnection = null;

        postParameters = "name="+ URLEncoder.encode(user.name,"UTF-8")
                +"&age="+URLEncoder.encode(user.age+"","UTF-8")
                +"&username="+URLEncoder.encode(user.username,"UTF-8")
                +"&password="+URLEncoder.encode(user.password,"UTF-8");

        if (postParameters != null) {
            Log.i("Post", "POST parameters: " + postParameters);
            try {
                URL urlToRequest = new URL(SERVER_ADDRESS);
                urlConnection = (HttpURLConnection) urlToRequest.openConnection();
                urlConnection.setReadTimeout(30000 /* milliseconds */);
                urlConnection.setConnectTimeout(30000 /* milliseconds */);
                urlConnection.setDoOutput(true);
                urlConnection.setRequestMethod("POST");
                urlConnection.setRequestProperty("Content-Type",
                        "application/x-www-form-urlencoded");
                urlConnection.setFixedLengthStreamingMode(
                        postParameters.getBytes().length);
                PrintWriter out = new PrintWriter(urlConnection.getOutputStream());
                out.print(postParameters.getBytes());
                out.close();

                // handle issues
                int statusCode = urlConnection.getResponseCode();
                Log.e("Response", "The response is: " + statusCode);

            } catch (MalformedURLException e) {
                // handle invalid URL
                Log.e("Response", "invalid URL");
            } catch (SocketTimeoutException e) {
                // hadle timeout
                Log.e("Response", "handle timeout");
            } catch (IOException e) {
                // handle I/0
                Log.e("Response", "handle IO problem");
            } finally {
                if (urlConnection != null) {
                    urlConnection.disconnect();
                }
            }
        }
        return null;
    }

代码未显示任何错误,记录的条目为

09-27 12:24:17.944 5006-5039/? E/Response﹕ The response is: 200 09-27 12:24:33.729 5006-5118/? I/Post﹕ POST parameters: name=vibha&age=25&username=vib&password=1234

但是当我检查数据库时,没有创建新记录

但是,如果我在文件中使用PHP代码并发布相同的参数,则会插入记录

我需要的帮助和指导是如何在HttpURLConnection类中传递post参数


共 (0) 个答案