无法解决Android中的POST请求

问题描述 投票:1回答:1

我知道大家已经问过这个问题很多次了。但它仍然给我带来了困难。

在收集了一些地方的代码:如 教程 我可以写这个。

我所做的:我已经检查了GET请求的代码的工作。它的工作。

private class Myworker extends AsyncTask<Void, Void, Void> {
    @Override
    protected Void doInBackground(Void... voids) {
        try {
            URL url = new URL("myurl");
            org.json.JSONObject df = new org.json.JSONObject();
            df.put("amount", "50");

            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(15000);
            conn.setConnectTimeout(15000);
            conn.setRequestMethod("POST");
            conn.setDoInput(true);
            conn.setDoOutput(true);

            try {
                OutputStream os = conn.getOutputStream();
                BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
                writer.write(getPostDataString(df));

                writer.flush();
                writer.close();
                os.close();

                int responseCode = conn.getResponseCode();
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                    StringBuilder stringBuilder = new StringBuilder();
                    String line;
                    while ((line = bufferedReader.readLine()) != null) {
                        stringBuilder.append(line).append("\n");
                    }
                    bufferedReader.close();
                    System.out.println("n " + new String(stringBuilder));
                }
            } finally {
                conn.disconnect();
            }
        } catch (Exception e) {
            System.out.println("Unable *******");
            e.printStackTrace();
        }
        return null;
    }
}

    public String getPostDataString(org.json.JSONObject params) throws Exception {
        StringBuilder result = new StringBuilder();
        boolean first = true;

        Iterator itr = params.keys();

        while (itr.hasNext()) {
            String key = (String) itr.next();
            Object value = params.get(key);

            if (first)
                first = false;
            else
                result.append("&");

            result.append(URLEncoder.encode(key, "UTF-8"));
            result.append("=");
            result.append(URLEncoder.encode(value.toString(), "UTF-8"));
        }
        return result.toString();
    }
}

错误。int responseCode=conn.getResponseCode() 也被返回为415。

D/NetworkSecurityConfig: No Network Security Config specified, using platform default

请帮助我

java android api post request
1个回答
1
投票

415是不支持的媒体类型,这可能是由于你没有正确设置内容-类型头。

尝试添加

conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

将来你可能会想试试http客户端库,比如apache httpcomponents或者google-http-client,因为它们更容易使用。

© www.soinside.com 2019 - 2024. All rights reserved.