java - 无法在 Java 中发送正确的 POST 请求 (Android Studio)

标签 java android android-studio http-post

我正在创建一个用于提问/回答问题的应用程序。 当我提问时,我遇到了 POST 请求的问题。

我尝试在终端中使用类似的东西

curl -H "Content-Type: application/json" -d '{"firstName":"Chris", "lastName": "Chang", "email": "support@mlab.com"}' http://your-app-name.herokuapp.com/contacts

效果很好。

但是当我尝试在 AndroidStudio 中发送 POST 请求时,我的参数(例如姓名、姓氏、电子邮件等)不会发送。 我尝试使用 https://github.com/kevinsawicki/http-request 。请求已发送(我知道,因为它显示了请求的日期),但没有任何参数。

我的代码应该更改哪些内容才能正常工作?

Map<String, String> data = new HashMap<String, String>();
data.put("firstName", "Gena");
data.put("lastName", "Bukin");
if (HttpRequest.post("https://safe-citadel-91138.herokuapp.com/questions").form(data).created())
System.out.println("User was created");

最佳答案

尝试这样..

Map<String, Object> params = new LinkedHashMap<>();
params.put("firstName", "Gena");
params.put("lastName", "Bukin");


JSONObject jsonObject = POST("https://safe-citadel-91138.herokuapp.com/questions", params);
    /**
         * Method allows to HTTP POST request to the server to send data to a specified resource
         * @param serverURL URL of the API to be requested
         * @param params parameter that are to be send in the "body" of the request Ex: parameter=value&amp;also=another
         * returns response as a JSON object
         */
        public JSONObject POST(String serverURL, Map<String, Object> params) {
            JSONObject jsonObject = null;
            try {
                URL url = new URL(serverURL);

                Log.e(TAG, params.toString());
                StringBuilder postData = new StringBuilder();

                for (Map.Entry<String, Object> param : params.entrySet()) {
                    if (postData.length() != 0) postData.append('&');
                    postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
                    postData.append('=');
                    postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
                }
                Log.e("POST", serverURL + ":" + params.toString());
                byte[] postDataBytes = postData.toString().getBytes("UTF-8");
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setRequestProperty("Content-Type", "application/json");
                connection.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
                connection.setRequestMethod("POST");
                connection.setConnectTimeout(5000);
                connection.setUseCaches(false);
                connection.setDoOutput(true);
                connection.getOutputStream().write(postDataBytes);
                connection.connect();

                int statusCode = connection.getResponseCode();
                if (statusCode == 200) {
                    sb = new StringBuilder();
                    reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                    String line;
                    while ((line = reader.readLine()) != null) {
                        sb.append(line + "\n");
                    }
                }
                jsonObject = new JSONObject(sb.toString());
            } catch (Exception e) {
                //e.printStackTrace();
            }
            return jsonObject;
        }

关于java - 无法在 Java 中发送正确的 POST 请求 (Android Studio),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37525153/

相关文章:

java - JSOUP:无法解析方法标题()

java - 在另一个maven项目中使用测试类

java - Apache POI 中的负单元格值样式

android - 在不丢失方位和倾斜的情况下对 MapView v2 相机进行动画处理

android - "Service MeasurementBrokerService is in use"在我的申请过程中显示

android - Recyclerview(在Recyclerview上获取项目)

android - Gradle 错误 - 找不到参数/路径/to/storefile 的方法 storeFile()

java - 需要有关我的 fragment 的帮助

android - OkHttp 和 Retrofit 2 缓存和离线使用

java - 显示错误\. java.lang.NullPointerException : Attempt to invoke interface method 'java.lang.Object java.util.List.get(int)' on a null object reference