gpt4 book ai didi

java - 如何在Android中读取HttpResponse?

转载 作者:行者123 更新时间:2023-12-01 21:53:22 25 4
gpt4 key购买 nike

我正在尝试将音频文件上传到我的网络服务器。但不知道如何阅读回复。这是非常简化的 test.php:

<?php 
echo 'I want to see this in the Toast';
?>

fff 这是我的 onClick,它必须将文件发送到网络服务器并获得响应:

public void send(View v){
Uri uri = new Uri.Builder().scheme("http").authority("sub.domain.nl").path("test.php")
.appendQueryParameter("action", "sendMessage")
.appendQueryParameter("idto", "18")
.appendQueryParameter("idfrom", "36")
.appendQueryParameter("type", "audio")
.build();
String urlString = uri.toString();
new SendAudioTask().execute(urlString);
}


private class SendAudioTask extends AsyncTask<String, Integer, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
}

@Override
protected String doInBackground(String... params) {
String url = params[0];
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath(),
"/audio.3gpp");

HttpResponse response = null;

try {
HttpClient httpclient = new DefaultHttpClient();

HttpPost httppost = new HttpPost(url);

InputStreamEntity reqEntity = new InputStreamEntity(
new FileInputStream(file), -1);
reqEntity.setContentType("binary/octet-stream");
reqEntity.setChunked(true);
httppost.setEntity(reqEntity);
response = httpclient.execute(httppost);
} catch (Exception e) {
publishProgress(1);
}
return response.toString();
}

@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
Toast.makeText(MainActivity.this, "Dev message: = " + values[0], Toast.LENGTH_SHORT).show();
}

@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Toast.makeText(MainActivity.this, result, Toast.LENGTH_SHORT).show();
}
}

onPostExecute() 中的 Result.toString() 是

org.apache.http.message.basicHttpRespons@43b4cc68

如果 toString() 是读取响应的正确方法。我的代码有什么问题吗?我的代码不执行publishProgress。

最佳答案

HttpEntity entity = httpResponse.getEntity();
InputStream is = entity.getContent();
String result = convertStreamToString(is);

private static String convertStreamToString(InputStream is) {

BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();

String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append((line + "\n"));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}

关于java - 如何在Android中读取HttpResponse?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34815284/

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