我正在编写函数时遇到问题.我正在尝试将输入流转换为字符串值.我写了两个函数,我试图提取String值,但我的Log.e响应返回NULL.以下是我的语法.我究竟做错了什么?谢谢
public JSONArray GetCityDetails(String StateID) {
@SuppressWarnings("deprecation")
String url = "http://mywebsite.com/getCity.php?StateID="+URLEncoder.encode(StateID);
HttpEntity httpEntity = null;
try{
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
httpEntity = httpResponse.getEntity();
} catch(ClientProtocolException e){
e.printStackTrace();
} catch(IOException e){
e.printStackTrace();
}
JSONArray jsonArray = null;
if(httpEntity !=null){
try{
InputStream entityResponse = httpEntity.getContent();
// not working
String entityResponseAfterFunctionCall2 = readFully(entityResponse);
// not working
String entityResponseAfterFunctionCall3 = letsDoThisAgain(entityResponse);
Log.e("Entity Response Dude: ", entityResponseAfterFunctionCall3);
jsonArray = new JSONArray(entityResponseAfterFunctionCall3);
} catch(JSONException e){
e.printStackTrace();
} catch(IOException e){
e.printStackTrace();
}
}
return jsonArray;
}
public String readFully(InputStream entityResponse) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length = 0;
while ((length = entityResponse.read(buffer)) != -1) {
baos.write(buffer, 0, length);
}
return baos.toString();
}
public String letsDoThisAgain(InputStream entityResponse){
InputStreamReader is = new InputStreamReader(entityResponse);
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(is);
try {
String read = br.readLine();
while(read !=null){
sb.append(read);
read = br.readLine();
}
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
}
Run Code Online (Sandbox Code Playgroud)
小智 7
if(inputStream != null)
{
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
String line;
try {
br = new BufferedReader(new InputStreamReader(inputStream));
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return sb.toString();
}
else
{
return "";
}
Run Code Online (Sandbox Code Playgroud)
您的readFully调用将使用系统的默认字符编码将字节缓冲区转换为字符串。这不是你想要发生的事情。
您应该在调用中使用显式字符集toString。编码通常在 HTTP 请求标头中指定。
UTF-8这是如何转换编码字符串的示例
return baos.toString( "UTF-8" );
Run Code Online (Sandbox Code Playgroud)
第二个问题是,一旦您在调用中使用了 InputString readFully,letsDoThisAgain将没有任何内容可读取,因为 InputStream 将位于 EOF 处。
| 归档时间: |
|
| 查看次数: |
10260 次 |
| 最近记录: |