您好我有一个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();
时似乎发生了问题。
答案 0 :(得分:0)
您可能正在回收连接
尝试在连接前添加urlConnection.setRequestProperty("Connection", "close");