接到请求后,与Android的HttpURLConnection的GET(Post requests

2019-10-18 23:49发布

我想上传一个二进制文件(一个序列化对象)到我的谷歌应用程序引擎服务器,但我只收到GET请求。 这里是我的代码:

private void sendPostRequest() {
if (!isConnected()) {
    return;
}

File file = new File(this._context.getFilesDir() + "/" + FILE_NAME);
FileInputStream fis;
try {
    fis = new FileInputStream(file);
    int length = fis.available();
    URL url = new URL(URL);
    HttpURLConnection connection = (HttpURLConnection) url
            .openConnection();
    connection.setRequestMethod("POST");
    connection.setDoOutput(true);
    connection.setDoInput(true);
    connection.setInstanceFollowRedirects(false);
    connection.setRequestProperty("Content-Type",
            "application/x-www-form-urlencoded");
    connection.setRequestProperty("charset", "utf-8");
    String urlParameters = URLEncoder.encode("family", "UTF-8") + "="
            + URLEncoder.encode("ohayon", "UTF-8");
    byte[] buffer = new byte[length];
    urlParameters += "&data=" + fis.read(buffer);
    connection.setRequestProperty("Content-Length",
            "" + Integer.toString(urlParameters.getBytes().length));
    connection.setUseCaches(false);

    // BufferedWriter we = new BufferedWriter(new OutputStreamWriter(
    // connection.getOutputStream(), "UTF-8"));
    DataOutputStream wr = new DataOutputStream(
            connection.getOutputStream());
    wr.write(urlParameters.getBytes());
    wr.flush();
    wr.close();
    connection.disconnect();
} catch (MalformedURLException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}
}

任何想法,我做错了什么? 还评论关于实施,将不胜感激,因为这是我在与Android的网络第一次尝试

谢谢!

文章来源: Post requests received as GET with android HttpURLConnection