如何通过POST请求在Java(Android应用)中将音频文件发送到服务器?

huangapple go评论118阅读模式
英文:

How to send audio file to server via POST request in Java (Android App)?

问题

  1. 我想在我的Java Android应用中通过POST请求将音频文件发送到服务器以下是我目前的代码但是它无法正常工作
  2. 我找到了这个实现了MultiPart Utility的类
  3. public class MultipartUtility {
  4. private static final String LINE_FEED = "\r\n";
  5. private HttpURLConnection httpConn;
  6. private String charset;
  7. private OutputStream outputStream;
  8. private PrintWriter writer;
  9. private final String boundary;
  10. // ...(省略部分代码)...
  11. public List<String> finish() throws IOException {
  12. List<String> response = new ArrayList<String>();
  13. writer.append(LINE_FEED).flush();
  14. writer.append("--" + boundary + "--").append(LINE_FEED);
  15. writer.close();
  16. // 首先检查服务器的状态代码
  17. int status = httpConn.getResponseCode();
  18. if (status == HttpURLConnection.HTTP_OK) {
  19. BufferedReader reader = new BufferedReader(new InputStreamReader(
  20. httpConn.getInputStream()));
  21. String line = null;
  22. while ((line = reader.readLine()) != null) {
  23. response.add(line);
  24. }
  25. reader.close();
  26. httpConn.disconnect();
  27. } else {
  28. throw new IOException("Server returned non-OK status: " + status);
  29. }
  30. return response;
  31. }
  32. }
  33. 想要使用以下客户端代码向服务器发送POST请求
  34. String requestURL = "http://0.0.0.0:5000/test";
  35. try {
  36. com.eng.elfarsisy.recored.MultipartUtility multipart = new com.eng.elfarsisy.recored.MultipartUtility(requestURL, charset);
  37. multipart.addHeaderField("User-Agent", "CodeJava");
  38. multipart.addHeaderField("Test-Header", "Header-Value");
  39. multipart.addFormField("description", "Cool Pictures");
  40. multipart.addFormField("keywords", "Java,upload,Spring");
  41. multipart.addFilePart("fileUpload", uploadFile1);
  42. List<String> response = multipart.finish();
  43. System.out.println("SERVER REPLIED:");
  44. for (String line : response) {
  45. System.out.println(line);
  46. }
  47. } catch (IOException ex) {
  48. System.err.println(ex);
  49. }
  50. 但是我得到了以下响应
  51. `I/System.out: (HTTPLog)-Static: isSBSettingEnabled false`
  52. `I/System.out: (HTTPLog)-Static: isSBSettingEnabled false`
  53. `W/System.err: java.net.SocketException: Permission denied`
  54. 如何修复这个问题任何想法将不胜感激
英文:

I want to send an audio file to a server via a POST request in my Java Android App. The following code is what I currently have, however, it is not working.

I have found this class implementing a MultiPart Utility:

  1. public class MultipartUtility {
  2. private static final String LINE_FEED = &quot;\r\n&quot;;
  3. private HttpURLConnection httpConn;
  4. private String charset;
  5. private OutputStream outputStream;
  6. private PrintWriter writer;
  7. private final String boundary;
  8. public MultipartUtility(String requestURL, String charset)
  9. throws IOException {
  10. this.charset = charset;
  11. // creates a unique boundary based on time stamp
  12. boundary = &quot;===&quot; + System.currentTimeMillis() + &quot;===&quot;;
  13. URL url = new URL(requestURL);
  14. httpConn = (HttpURLConnection) url.openConnection();
  15. httpConn.setUseCaches(false);
  16. httpConn.setDoOutput(true); // indicates POST method
  17. httpConn.setDoInput(true);
  18. httpConn.setRequestProperty(&quot;Content-Type&quot;,
  19. &quot;multipart/form-data; boundary=&quot; + boundary);
  20. httpConn.setRequestProperty(&quot;User-Agent&quot;, &quot;CodeJava Agent&quot;);
  21. httpConn.setRequestProperty(&quot;Test&quot;, &quot;Bonjour&quot;);
  22. outputStream = httpConn.getOutputStream();
  23. writer = new PrintWriter(new OutputStreamWriter(outputStream, charset),
  24. true);
  25. }
  26. public void addFormField(String name, String value) {
  27. writer.append(&quot;--&quot; + boundary).append(LINE_FEED);
  28. writer.append(&quot;Content-Disposition: form-data; name=\&quot;&quot; + name + &quot;\&quot;&quot;)
  29. .append(LINE_FEED);
  30. writer.append(&quot;Content-Type: text/plain; charset=&quot; + charset).append(
  31. LINE_FEED);
  32. writer.append(LINE_FEED);
  33. writer.append(value).append(LINE_FEED);
  34. writer.flush();
  35. }
  36. public void addFilePart(String fieldName, File uploadFile)
  37. throws IOException {
  38. String fileName = uploadFile.getName();
  39. writer.append(&quot;--&quot; + boundary).append(LINE_FEED);
  40. writer.append(
  41. &quot;Content-Disposition: form-data; name=\&quot;&quot; + fieldName
  42. + &quot;\&quot;; filename=\&quot;&quot; + fileName + &quot;\&quot;&quot;)
  43. .append(LINE_FEED);
  44. writer.append(
  45. &quot;Content-Type: &quot;
  46. + URLConnection.guessContentTypeFromName(fileName))
  47. .append(LINE_FEED);
  48. writer.append(&quot;Content-Transfer-Encoding: binary&quot;).append(LINE_FEED);
  49. writer.append(LINE_FEED);
  50. writer.flush();
  51. FileInputStream inputStream = new FileInputStream(uploadFile);
  52. byte[] buffer = new byte[4096];
  53. int bytesRead = -1;
  54. while ((bytesRead = inputStream.read(buffer)) != -1) {
  55. outputStream.write(buffer, 0, bytesRead);
  56. }
  57. outputStream.flush();
  58. inputStream.close();
  59. writer.append(LINE_FEED);
  60. writer.flush();
  61. }
  62. public void addHeaderField(String name, String value) {
  63. writer.append(name + &quot;: &quot; + value).append(LINE_FEED);
  64. writer.flush();
  65. }
  66. public List&lt;String&gt; finish() throws IOException {
  67. List&lt;String&gt; response = new ArrayList&lt;String&gt;();
  68. writer.append(LINE_FEED).flush();
  69. writer.append(&quot;--&quot; + boundary + &quot;--&quot;).append(LINE_FEED);
  70. writer.close();
  71. // checks server&#39;s status code first
  72. int status = httpConn.getResponseCode();
  73. if (status == HttpURLConnection.HTTP_OK) {
  74. BufferedReader reader = new BufferedReader(new InputStreamReader(
  75. httpConn.getInputStream()));
  76. String line = null;
  77. while ((line = reader.readLine()) != null) {
  78. response.add(line);
  79. }
  80. reader.close();
  81. httpConn.disconnect();
  82. } else {
  83. throw new IOException(&quot;Server returned non-OK status: &quot; + status);
  84. }
  85. return response;
  86. }
  87. }

and want to send a POST request to a server with this client code:

  1. String requestURL = &quot;http://0.0.0.0:5000/test&quot;;
  2. try {
  3. com.eng.elfarsisy.recored.MultipartUtility multipart = new com.eng.elfarsisy.recored.MultipartUtility(requestURL, charset);
  4. multipart.addHeaderField(&quot;User-Agent&quot;, &quot;CodeJava&quot;);
  5. multipart.addHeaderField(&quot;Test-Header&quot;, &quot;Header-Value&quot;);
  6. multipart.addFormField(&quot;description&quot;, &quot;Cool Pictures&quot;);
  7. multipart.addFormField(&quot;keywords&quot;, &quot;Java,upload,Spring&quot;);
  8. multipart.addFilePart(&quot;fileUpload&quot;, uploadFile1);
  9. List&lt;String&gt; response = multipart.finish();
  10. System.out.println(&quot;SERVER REPLIED:&quot;);
  11. for (String line : response) {
  12. System.out.println(line);
  13. }
  14. } catch (IOException ex) {
  15. System.err.println(ex);
  16. }

However I am getting this response:

I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
W/System.err: java.net.SocketException: Permission denied

How can I fix this? Any ideas would be greatly appreciated.

答案1

得分: 0

你是否已将此权限添加到清单文件中?

  1. <uses-permission android:name="android.permission.INTERNET"/>
英文:

Have you added this permission to your manifest?

  1. &lt;uses-permission android:name=&quot;android.permission.INTERNET&quot;/&gt;

huangapple
  • 本文由 发表于 2020年4月8日 03:20:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/61087785.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定