无法使用 HttpURLConnection 将参数写入 url

Unable to write the parameters to url using HttpURLConnection

我正在尝试 post 一个带参数的 HTTP URL。我已经使用 appendQueryPrameters 附加了参数,但是 build() 之后的语句被跳过并且控件从 AsyncTask 出来。下面是 AsyncTask[=21= 的片段]

private class MyAsyncTask extends AsyncTask<String, Integer, String> {
        @Override
        protected String doInBackground(String... params) {
            // TODO Auto-generated method stub


            String givenDob = params[0];
            String givensurname = params[1];
            String givenCaptcha = params[2];
            String response = "";
            try {
                Uri.Builder builder = new Uri.Builder()
                        .appendQueryParameter("dateOfBirth", givenDob)
                        .appendQueryParameter("userNameDetails.surName", givensurname)
                        .appendQueryParameter("captchaCode", givenCaptcha);
                String query = builder.build().toString();
                PrintWriter out = new PrintWriter(connection.getOutputStream());
                out.print(query);
                out.close();
                int responseCode = connection.getResponseCode();
                Log.d("responseCode", String.valueOf(responseCode));

   /*             BufferedWriter writer = new BufferedWriter(
                      new OutputStreamWriter(connection.getOutputStream(), "ISO-8859-1"));

                writer.write(query);
               writer.flush();
               writer.close();
    */
                connection.getOutputStream().close();
                if (responseCode == HttpsURLConnection.HTTP_OK) {
                    String line;
                    BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                    while ((line = br.readLine()) != null) {
                        response += line;

                        Log.d("response", response);
                    }
                } else {
                    response = "";
                }
            } catch (IOException e) {
                e.printStackTrace();
            }


            return response;
        }

        @Override
        protected void onPostExecute(String s) {
            Log.d("res", s);
        }

    }

我尝试使用 PrintWriter also.Still 它跳过了 String query = builder.build().toString();

行之后的语句的执行

PS:我在另一个 AsyncTask 中打开了 HttpURLconnection 并在 onCreate() 上调用了它下面是代码。

 URL url = new URL("https://myurl.com/path1/path2/path3.html");
            connection = (HttpsURLConnection) url.openConnection();
            connection.setReadTimeout(10000);
            connection.setConnectTimeout(15000);
            connection.setRequestMethod("POST");
            connection.setDoInput(true);
            connection.setDoOutput(true);

使用this参考

我将告诉您如何使用 HttpURL连接对象将参数发送到我的服务器:

            // Instantiate the connexion.
            URL url = new URL(_url);
            HttpURLConnection con;


            // Build data string to send to server:
            String data = StringUtils.paramsToUrlString(params);

            /* Obtain a new HttpURLConnection by calling URL.openConnection() and casting the result to HttpURLConnection.*/
            con = (HttpURLConnection)url.openConnection();
            // Activar método POST:
            // Instances must be configured with setDoOutput(true) if they include a request body.
            con.setDoOutput(true);
            // Data size known:
            con.setFixedLengthStreamingMode(data.getBytes("UTF-8").length);
            // Establecer application/x-www-form-urlencoded debido a la simplicidad de los datos
            //con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // NO SIRVE PARA UTF-8
            con.setRequestProperty("Accept-Charset", "UTF-8");
            con.getContentEncoding();

            // Set time out for both reading and writing operations.
            con.setConnectTimeout(30*1000);
            con.setReadTimeout(30*1000);

            // Read the response:
            // Upload a request body: Write data on the output stream (towards the server)
            OutputStream out = new BufferedOutputStream(con.getOutputStream());
            out.write(data.getBytes("UTF-8"));
            out.flush();
            out.close();

            // Store the input stream (server response):
            // If the response has no body, that method returns an empty stream.
            is = new BufferedInputStream(con.getInputStream());

            // Return JSON Object.
            jObj = castResponseToJson(is);

            // Disconnect: Release resources.
            con.disconnect();

而StringUtils.paramsToUrlString(params)是将参数转换成合适的URL字符串的方法:

/**
 * This method receives a ContentValues container with the parameter
 * and returns a well formed String to send the parameter throw Hppt.
 *
 * @param params Parameter to send to the server.
 * @return param1=param1value&param2=param2value&....paramX=paramXvalue.
 */
public static String paramsToUrlString (ContentValues params) {

    String data = "";

    Set<Map.Entry<String, Object>> s = params.valueSet();
    Iterator itr = s.iterator();

    Log.d("Constructing URL", "ContentValue Length : " + params.size());

    while(itr.hasNext())
    {
        Map.Entry me = (Map.Entry)itr.next();
        String key = me.getKey().toString();
        String value =  me.getValue().toString();

        try {
            data+=(URLEncoder.encode(key, "UTF-8")+"="+URLEncoder.encode(value, "UTF-8")+"&");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    // Removing last char from data:
    return (data.substring(0, data.length()-1));
}

paramsToUrlString(params) 方法接收的参数必须包含在 ContentValues 对象中,如下所示:

    ContentValues params = new ContentValues();
    params.put("Param1Name", "Param1Value");
    params.put("Param2Name", "Param2Value");
    params.put("Param3Name", "Param3Value");
 URL strUrl = new URL("https://myurl.com/path1/path2/path3.html?dateOfBirth=" + params[0] +
                    "&userNameDetails.surName=" + params[1] +
                    "&captchaCode=" + params[2]);

            Log.d("strUrl", String.valueOf(strUrl));

            URLConnection conn = strUrl.openConnection();

[这段代码稍微改动一下就可以了。但不幸的是,这个答案的 OP 删除了他的评论。]

编辑: 实际上我正在打开连接来获取验证码。使用上面的方法让我打开另一个连接,这让我出现了错误的验证码错误。所以这不是答案。

编辑2: 使用 cookimanager 帮助了我。 这里有更多