[英]How to read HttpResponse in Android?
我正在嘗試將音頻文件上傳到我的網絡服務器。 但是不知道如何讀取響應。 這是非常簡化的test.php:
<?php
echo 'I want to see this in the Toast';
?>
fff這是我的onClick,必須將文件發送到Web服務器並獲得響應:
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();
}
更改
return response.toString();
至
return EntityUtils.toString(response.getEntity());
那么getEntity()
做什么,
getEntity()
獲取此響應的消息實體(如果有)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.