从Android设备发出请求时出现意外状态行

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

嗨我有一个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();时问题似乎发生了。

java android http-post
1个回答
0
投票

可能你正在回收连接

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

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