无法使用HttpURLConnection

时间:2016-01-27 10:52:21

标签: android android-asynctask httpurlconnection

我正在尝试发布带有参数的HTTP网址。我已使用appendQueryPrameters添加参数但跳过build()后的语句并且控件来自AsyncTask。以下是AsyncTask

的摘录
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.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 作为参考

2 个答案:

答案 0 :(得分:1)

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

            // 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");

答案 1 :(得分:0)

 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删除了他的评论。]

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

EDIT2: 使用cookimanager帮助了我。 这里'更多 https://stackoverflow.com/a/35104167/5733855