请帮助我,如果响应代码是204
如何调用,应该再次致电服务器?
String command = ("http://api.railwayapi.com/live/train/" + m_train_Number + "/doj/" + m_year + m_month + m_day + "/apikey/tc9sc898/");
new JSONTask().execute(command);
public class JSONTask extends AsyncTask<String, String, LiveStationModel>
{
LiveStationModel liveStationModel = null;
protected LiveStationModel doInBackground(String... params) {
IOException e;
MalformedURLException e2;
List<LiveStationModel> myList = null;
Throwable th;
JSONException e3;
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
connection = (HttpURLConnection) new URL(params[0]).openConnection();
connection.connect();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
try {
StringBuffer buffer = new StringBuffer();
String str = "";
while (true) {
str = bufferedReader.readLine();
if (str == null) {
break;
}
buffer.append(str);
}
答案 0 :(得分:0)
你可以检查它是onPostExecute
方法,如:
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
//check your if condition here
}
答案 1 :(得分:0)
public class JSONTask extends AsyncTask<String, String, LiveStationModel>
{
int resp;
-------
connection.connect();
resp = connection.getResponseCode();
--------
}
现在覆盖onPostExecute,就像这样,
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if(resp == 204)
{
new JSONTask().execute(command);
}
else
{
//your code here
}
}
答案 2 :(得分:0)
在AsyncTask的onPostExecute方法中使用if条件。
答案 3 :(得分:0)
在你的onPostExecute方法中检查你是否得到了预期的结果,如果不是再次调用你的新JSONTask()。执行(命令);
喜欢
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
new JSONTask().execute(command);
}
答案 4 :(得分:0)
这将检查响应是否为204但是如果您想尝试另一个连接,disconnect
当前连接,然后使用不同的URL建立另一个连接;因为如果你重复你的网址,你会一次又一次地得到相同的结果(NO_CONTENT)。
public class JSONTask extends AsyncTask<String, String, LiveStationModel>
{
LiveStationModel liveStationModel = null;
protected LiveStationModel doInBackground(String... params) {
IOException e;
MalformedURLException e2;
List<LiveStationModel> myList = null;
Throwable th;
JSONException e3;
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
connection = (HttpURLConnection) new URL(params[0]).openConnection();
connection.connect();
if(connection.getResponseCode() == HttpURLConnection.HTTP_NO_CONTENT)
{
//do what you gonna do
}
如果你想重复,直到你得到内容 使用这样的循环:
try {
int code = connection.getResponseCode();
while(code == 204)
{
connection = (HttpURLConnection) new URL(params[?]).openConnection(); // Different Parameter here
connection.connect();
....
}