Android PHP JSON解析给出404错误但是获取数据

时间:2015-11-03 06:44:04

标签: php android json http-status-code-404

我遇到了一个让我很困惑的问题。所以,我正在将数据从mysql解析到我的android设备。事情是从服务器端,我收到404错误但数据已成功获取并填充在我的列表视图中。这是非常不利的,因为我必须绕过代码

StatusLine responseStatus = response.getStatusLine();
  if (responseStatus.getStatusCode() != 200) {}

负责检测实际的服务器错误。我从android端调用以获取json数据的链接是http://applink.skibzy.com/1/index.php?action=fetchdata,当我从浏览器调用url时,显示json编码数据并在服务器端注册http状态代码404。请帮助我解决这个尴尬但令人困惑的问题。涉及的相应文件是FetchBlogPostData.java,MainActivity.java和index.php

的index.php

<?php
require('db.php');
$action = $_GET['action'];

if ($action == 'fetchdata') {
$query = mysql_query('SELECT * FROM posts ORDER BY date DESC');
if (mysql_num_rows($query) >= '1') {
    $a = array();
    while ($b = mysql_fetch_array($query)) {
        $post = array();
        $post["title"] = $b['post_title'];
        //$post["who"] = DB_USER;
        array_push($a, $post);  
    }
    echo json_encode($a);
}
}
?>

MainActivity.java

public class MainActivity extends ListActivity implements FetchDataListener {

Constants constant;
Utils utils;

private ActionBarActivity action;
private ProgressBar dialog;
public TextView post_id;

@Override
protected void onCreate(Bundle savedInstanceState) {
    constant = new Constants();
    utils = new Utils(this);
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    dialog = (ProgressBar) findViewById(R.id.progressBar);

    initView();
}

private void initView() {
// show progress dialog
    dialog.setVisibility(View.VISIBLE);
    String url = "http://applink.skibzy.com/1/index.php?action=fetchdata";
    FetchBlogPostData task = new FetchBlogPostData(this);
    task.execute(url);
    //getListView().setOnClickListener(this);
}

@Override
public void onFetchComplete(List<BlogPostValue> data) {
    // dismiss the progress dialog
    if(dialog != null) dialog.setVisibility(View.GONE);
    post_id = (TextView) findViewById(R.id.postID);
    // create new adapter
    BlogPostAdapter adapter = new BlogPostAdapter(this, data);
    // set the adapter to list
    setListAdapter(adapter);
}
@Override
public void onFetchFailure(String msg) {
    // dismiss the progress dialog
    if(dialog != null) dialog.setVisibility(View.GONE);

    Bundle dataBundle = new Bundle();
    dataBundle.putString("error", msg);
    dataBundle.putString(constant.PREVIOUS_ACTIVITY, constant.THE_MAIN_ACTIVITY);
    Intent intent = new Intent(getApplicationContext(), ErrorActivity.class);
    intent.putExtras(dataBundle);
    startActivity(intent);
    finish();
}
}

FetchBlogPostData.java

public class FetchBlogPostData extends AsyncTask<String, Void, String> {
private final FetchDataListener listener;
private String msg;
public FetchBlogPostData(FetchDataListener listener) {
    this.listener = listener;
}
@Override
protected String doInBackground(String... params) {
    if(params == null) return null;
        // get url from params
        String url = params[0];
        try {
            HttpClient client = new DefaultHttpClient();
            HttpGet httpget = new HttpGet(url);

            HttpResponse response = client.execute(httpget);

            HttpEntity entity = response.getEntity();
            if(entity == null) {
                msg = "Try Again";
                return null;
            }

            InputStream is = entity.getContent();
            return streamToString(is);
        }
        catch(IOException e){
            msg = "No Internet Connection";
        }
    return null;
}
@Override
protected void onPostExecute(String sJson) {
    if (sJson == null) {
        if (listener != null) listener.onFetchFailure(msg);
        return;
    }
    try {
        // convert json string to json array
        JSONArray aJson = new JSONArray(sJson);
        // create apps list
        List<BlogPostValue> apps = new ArrayList<BlogPostValue>();
        for (int i = 0; i < aJson.length(); i++) {
            JSONObject json = aJson.getJSONObject(i);
            BlogPostValue app = new BlogPostValue();
            app.setID(json.getString("id"));
            app.setTitle(json.getString("title"));
            app.setExerpt(json.getString("exerpt"));
            app.setCreated(json.getString("created"));
            app.setTotalComments(json.getString("comments"));
            app.setCommentStatus(json.getString("comment_status"));
            app.setIcon(json.getString("thumbnail"));
            // add the app to apps list
            apps.add(app);
        }
        //notify the activity that fetch data has been complete
        if (listener != null) listener.onFetchComplete(apps);
    } catch (JSONException e) {
        msg = "Try Again";
        if (listener != null) listener.onFetchFailure(msg);
            return;
    }
}

/**
 * This function will convert response stream into json string
 * @param is respons string
 * @return json string
 * @throws IOException
 */
public String streamToString(final InputStream is) throws IOException{
    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) {
        throw e;
    }
    finally {
        try {
            is.close();
        }
        catch (IOException e) {
            throw e;
        }
    }
    return sb.toString();
}
}

0 个答案:

没有答案
相关问题