[英]Convert an inputstream to a string value in Java Android App
我正在編寫函數時遇到問題。 我正在嘗試將輸入流轉換為字符串值。 我寫了兩個函數,我試圖提取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();
}
}
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 "";
}
readFully
調用將使用系統的默認字符編碼將字節緩沖區轉換為String。 這不是你想要發生的事情。
您應該在toString
調用中使用顯式字符集。 編碼通常在HTTP請求標頭中指定。
以下是如何轉換UTF-8
編碼字符串的示例
return baos.toString( "UTF-8" );
你的第二個問題是,一旦你在readFully
調用中消耗了InputString, letsDoThisAgain
將沒有任何東西可以讀取,因為InputStream將處於EOF。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.