使用Android和HTTPSURLConnection

时间:2015-06-25 14:41:41

标签: java android httpurlconnection

我意识到有很多关于如何使用Android和HttpURLConnection发布json数据的帖子。然而,无论我尝试什么,我的POST身体似乎永远不会到达/神奇地消失。我希望有人能告诉我:

    // Encrypt the post data
    String ciphertext = Crypt.encrypt(postData, encryptionKey);

    int postDataLength = ciphertext.getBytes(StandardCharsets.UTF_8).length;
    byte[] bCipertext = ciphertext.getBytes(StandardCharsets.UTF_8);

    // Establish connection
    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();


    // Set the request method
    conn.setRequestMethod("POST");

    // Set headers
    for (String key : headers.keySet()) {
        conn.setRequestProperty(key, headers.get(key).trim());
    }

    // Set content type - always application/json!
    conn.setRequestProperty("Content-Type", "application/json");

    // Set UTF-8 as the charset
    conn.setRequestProperty("Accept-Charset", "UTF-8");

    conn.addRequestProperty("Content-Type", "application/" + "POST");

    // Don't cache data
    conn.setUseCaches(false);

    // Expect output
    conn.setDoOutput(true);

    if (!postData.isEmpty()) {
        conn.setDoInput(true);
        // Set content length
        conn.setFixedLengthStreamingMode(postDataLength);

        PrintWriter out = new PrintWriter(conn.getOutputStream());
        out.print(ciphertext);
        out.close();
    }

示例密文:

iMUPu3dJZRtwofMAeAzr5OvuNU2jg8kJL4I3LEtidlD18JG3ijg5m9vMON-Jndqt3fQLPotORB3ibmWl3-ia3lX5RyJIwPi7CCbNhkoVYHZEMktgC_N_6hqu4hYCMieLxvI93NwGMAsNpd00TNGFVSf0G3blpgRQ-gM5doxq6WRwkGlspZgHgQBK0GhXs3tNDGuBTYMJZHo3lKVR6k5Nky9JfeSyat7B7wO1-dFbVqr9DOy16mjRSlVKPzY_x1P63e9CQfnAc1sP8Yc2rvVXToC_Aq_OyQR1FZxHWi3Z9wA =,== J83haIWVSXDmtQ3UxPzaFQ

编辑: 问题仍然存在于OKHttp:

 Request request = new Request.Builder()
            .url(url)
            .post(RequestBody.create(MediaType.parse("text/plain; charset=utf-8"), ciphertext))
            .build();

    OkHttpClient client = new OkHttpClient();

    Response response = client.newCall(request).execute();

    System.out.println(ciphertext);

    String output = response.body().string();
    System.out.println(output);

    // Decrypt
    String decryptedResponse = null;
    try {
        decryptedResponse = Crypt.decrypt(output.toString(), encryptionKey).trim();
    } catch(Exception e) {
        // If the response wasn't encrypted, then we will receive an exception
        decryptedResponse = output.toString();
    }

    HttpResponse resp = new HttpResponse();
    resp.setStatus(response.code());

接收请求的PHP本质上就是这样:

的print_r($ _ POST);

1 个答案:

答案 0 :(得分:0)

您应该考虑使用第三方库来处理HTTP请求。例如,okhttp显着减少了代码开销和数量或错误:

String postBody = ""
    + "Releases\n"
    + "--------\n"
    + "\n"
    + " * _1.0_ May 6, 2013\n"
    + " * _1.1_ June 15, 2013\n"
    + " * _1.2_ August 11, 2013\n";

Request request = new Request.Builder()
    .url("https://api.github.com/markdown/raw")
    .post(RequestBody.create(MEDIA_TYPE_MARKDOWN, postBody))
    .build();

Response response = client.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

System.out.println(response.body().string());

此摘录摘自:https://github.com/square/okhttp/wiki/Recipes