java - 从 Android 设备发出发布请求时出现意外的状态行

标签 java android http-post

您好,我有一个 Android 应用程序需要连接到 API(当前在本地运行)来对用户进行身份验证,因此我尝试发送一个以 JSON 对象作为请求正文的 POST 请求,但每当我尝试登录时都会收到以下错误:

Unexpected status line: ��
           java.net.ProtocolException: Unexpected status line: ��

这是我的代码:

    String API_URL = "http://10.0.2.2:8443/api/";
        try {
            URL url = new URL(API_URL);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            try {
                urlConnection.setDoOutput(true);
                urlConnection.setRequestMethod("POST");
                urlConnection.setRequestProperty("Content-Type", "application/json");
                urlConnection.connect();

                JSONObject jsonObject = new JSONObject();
                jsonObject.put("customerId", 1);
                jsonObject.put("password" , mPassword);
                jsonObject.put("username" , mEmail);

                DataOutputStream wr = new DataOutputStream(urlConnection.getOutputStream());
                wr.writeBytes(jsonObject.toString());
                Log.d("REQUEST BODY", jsonObject.toString());
                wr.flush();
                wr.close();

                int response = urlConnection.getResponseCode();
                Log.d("RESPONSE", String.valueOf(response));
                if(response == HttpURLConnection.HTTP_OK) {
                    InputStream bis = new BufferedInputStream(urlConnection.getInputStream());
                    return getStringFromInputStream(bis);
                }
            }
            finally{
                urlConnection.disconnect();
            }
        }
        catch(Exception e) {
            Log.e("ERROR", e.getMessage(), e);
            return null;
        }

谁能告诉我我可能做错了什么?谢谢!

编辑

不确定这是否有帮助,但当我调用 urlConnection.getResponseCode(); 时似乎会出现问题。

最佳答案

可能您正在回收连接

尝试在连接之前添加 urlConnection.setRequestProperty("Connection", "close");

关于java - 从 Android 设备发出发布请求时出现意外的状态行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43102803/

相关文章:

python - 使用 Mautic API,如何在创建电子邮件时发送参数 "lists"?

java - 分析内存时使用哪个 GC?

android - 如何耦合 MultipartEntity 和 List 数组以在 android 中发送 httppost

java - ScheduledExecutor服务超时后结束

Android 手指同时旋转、缩放和移动图像?

Android 选项菜单在查看寻呼机上删除

java - 根据某些规则替换 EditText 中的字母

angular - 如何在 Angular 中的 HTTP post 请求中传递 url 中的查询参数

java - java 8中两个列表的合并函数

java - 将二维数组中每行的 null 元素移动到该行的末尾