您好,我有一个 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/