我正在尝试通过API发送短信,但显示错误java.io.IOException:流关闭这是我正在使用的代码:
package com.pyprestaurants;
import android.os.StrictMode;
import android.util.Log;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
public class SendMessage extends Thread {
String message;
String number;
SendMessage(String message, String number){
this.message = message;
this.number = number;
}
@Override
public void run() {
try {
// Construct data
String apiKey = "apikey=" + "nZ0ZOkGeO3U-lkmMqZZuUgKmjjrpCf6v3WMoBV3jWG";
String message = "&message=" + this.message;
String sender = "&sender=" + "PYPRES";
String numbers = "&numbers=" + this.number;
// Send data
HttpURLConnection conn = (HttpURLConnection) new
URL("https://api.textlocal.in/send/?").openConnection();
String data = apiKey + numbers + message + sender;
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Length", Integer.toString(data.length()));
conn.getOutputStream().write(data.getBytes(StandardCharsets.UTF_8));
final BufferedReader rd = new BufferedReader(new
InputStreamReader(conn.getInputStream()));
rd.close();
String line;
String msg="";
while ((line = rd.readLine()) != null) {
msg = msg+line;
Log.d("TAG","the message is "+line);
}
} catch (Exception e) {
Log.d("TAG- Error msg ",e+"");
}
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
}
我有各种各样的活动,希望通过它们发送SMS。因此,我做了一个单独的使用线程的类。每当我想发送消息时,我都会使用它来调用SendMessage类的函数(上面提供了其代码)。现在问题出在某些活动中,它正在发送消息,但是在某些情况下,它显示了错误:
java.io.IOException:流已关闭
我非常困惑,为什么相同的代码可以一次运行而另一次却显示错误。如果有人知道发生了什么错误,请告诉我。
我认为问题是您在rd.close();之后调用rd.readLine())。尝试将rd.close()方法进一步移回,以便在关闭它之前完成对rd的所有调用。
您在阅读之前关闭输入流
InputStreamReader(conn.getInputStream()));
rd.close();
String line;