HttpUrlConnection在Android 2.3姜饼中表现不同
我被难住了。自从Android 1.5以来,我一直在使用相同的HttpUrlConnection代码从我的服务器检索JSON。突然间,2.3就不起作用了,我不明白为什么 这是我的密码:HttpUrlConnection在Android 2.3姜饼中表现不同,android,Android,我被难住了。自从Android 1.5以来,我一直在使用相同的HttpUrlConnection代码从我的服务器检索JSON。突然间,2.3就不起作用了,我不明白为什么 这是我的密码: try { HttpURLConnection conn = (HttpURLConnection)(new URL(Constants.SERVER_URL + path)).openConnection(); c
try {
HttpURLConnection conn =
(HttpURLConnection)(new URL(Constants.SERVER_URL + path)).openConnection();
conn.setAllowUserInteraction(false); // no user interact [like pop up]
conn.setDoOutput(true); // want to send
conn.setDoInput(true);
conn.setRequestMethod( "POST" );
conn.setRequestProperty( "Content-type", "application/x-www-form-urlencoded" );
conn.setRequestProperty( "Accept", "application/json,text/html,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5" );
conn.setRequestProperty( "Accept-Charset", "UTF-8" );
conn.setRequestProperty("Connection", "Keep-Alive");
DataOutputStream pw = new DataOutputStream (conn.getOutputStream());
pw.writeBytes(requestString);
pw.flush();
pw.close();
if (conn.getResponseCode() == 200) {
InputStream in = new BufferedInputStream(conn.getInputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(in));
StringBuffer stringBuffer = new StringBuffer();
while(br.ready()){
stringBuffer.append(br.readLine());
}
br.close();
in.close();
return stringBuffer.toString();
} else {
return badResponse;
}
} catch (Exception ioe) {
return ERROR_MAKING_CONNECTION;
}
但是,当我运行conn.getInputStream().available()时,返回的响应代码是200,结果是-1。在除2.3之外的每一个android api上,conn.getInputStream().available()都会返回一个重要的响应
有什么想法吗?你能检查一下
conn.getInputStream().read(buf)
是否也返回-1吗available()
只返回在不阻塞其他线程的情况下可以读取的字节数。大多数时候,在任何地方使用它都是一个坏主意。我想返回-1是一种有效的行为,即使有数据可以读取。谢谢,Alex。你让我走对了路。无论出于何种原因,在2.3中,BufferedReader.ready()不会返回true,即使有要读取的内容。我将while(br.ready())切换到while(line=br.readline)!=null),现在它又开始工作了。想想看吧