【发布时间】:2017-06-27 22:54:43
【问题描述】:
我正在尝试使用脚本来实现登录活动。该脚本正在运行,我已经在邮递员应用程序中测试了该脚本。我以 json 格式发送数据,服务器以 json 格式发送响应。当我尝试阅读响应时,它始终为空。有人可以帮忙吗?
@Override
protected String doInBackground(String... params) {
String data="";
JSONObject jsonobj = new JSONObject();
JSONObject Data=new JSONObject();
try {
Data.put("service","emailsignin");
Data.put("email_id",mEmail);
Data.put("password",mPassword);
Data.put("device_token","ABCD");
Data.put("device_type","A");
Data.put("user_type_id","2");
jsonobj.put("data",Data);
} catch (JSONException e) {
e.printStackTrace();
}
HttpURLConnection httpURLConnection = null;
BufferedReader reader=null;
String write_data=String.valueOf(jsonobj);
Log.e("write_data:",write_data);
try {
httpURLConnection = (HttpURLConnection) new URL(params[0]).openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoInput(true);
Writer writer = new BufferedWriter(new OutputStreamWriter(httpURLConnection.getOutputStream(), "UTF-8"));
writer.write(write_data);
writer.close();
InputStream inputStream = new BufferedInputStream(httpURLConnection.getInputStream());
reader = new BufferedReader(newInputStreamReader(inputStream));
StringBuilder buffer = new StringBuilder();
String inputLine;
while ((inputLine = reader.readLine()) != null) {
Log.e("LoginActivity:",inputLine);
buffer.append(inputLine).append("\n");
}
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
Log.e("LoginActivity:","input string empty");
return null;
}
data = buffer.toString();
Log.e("Response is:",data);
try {
return data;
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}
catch (IOException e) {
e.printStackTrace();
}
finally {
if (httpURLConnection != null) {
httpURLConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e("Log In:", "Error closing stream", e);
}
}
}
return null;
}
【问题讨论】:
-
您可能只需要添加以下属性:
httpURLConnection.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); -
准确无误。这里没有“始终为空的输入流”或“响应......始终为空”。有一个 empty 响应,它由 your code translated 为 null。或者可能是您未在此处报告的
IOException,之后,您的代码 再次返回 null。一个try/catch围绕一个仅仅return声明是完全没有意义的。