gpt4 book ai didi

java - 在 Java Android App 中将输入流转换为字符串值

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:20:51 28 4
gpt4 key购买 nike

我在编写函数时遇到问题。我正在尝试将输入流转换为字符串值。我写了两个函数,我试图提取字符串值,但我的 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 "";
}

关于java - 在 Java Android App 中将输入流转换为字符串值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25983425/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com