Android:使用异步任务的JSON解析器(GET和POST方法)

4

我只是想检查一下这个带有异步任务的JSON解析器是否正确完成?当我把这段代码放到我的Eclipse中时,这个(method.equals("POST"))被下划线标红了。并且提示'method'无法解决。有什么建议或帮助吗?谢谢。

public class JSONParser {

  static InputStream is = null;
  static JSONObject jObj = null;
  static String json = "";
  String url=null;
     List<NameValuePair> nvp=null;
     // constructor
     public JSONParser() {

   }

  // function get json from url
  // by making HTTP POST or GET method
   public JSONObject makeHttpRequest(String url, String method,
        List<NameValuePair> params) {
      BackGroundTask Task= new BackGroundTask(url, method,  params);
    try {
        return Task.execute().get();
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return null;
    } catch (ExecutionException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return null;
    }
}
public class BackGroundTask extends AsyncTask<String, String, JSONObject>{
    List<NameValuePair> postparams= new ArrayList<NameValuePair>();
    String URL=null;
public BackGroundTask(String url, String method, List<NameValuePair> params) {
        URL=url;
        postparams=params;
    }
    @Override
    protected JSONObject doInBackground(String... params) {
        // TODO Auto-generated method stub
        // Making HTTP request
        try {
    // Making HTTP request 
        // check for request method

    if(method.equals("POST")){
            // request method is POST
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(postparams));

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

        }else if(method == "GET"){
            // request method is GET
            DefaultHttpClient httpClient = new DefaultHttpClient();
            String paramString = URLEncodedUtils.format(postparams, "utf-8");
            url += "?" + paramString;
            HttpGet httpGet = new HttpGet(url);

            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();
        }           

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {

        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON String
    return jObj;

   }
 }
}
2个回答

11

你忘记在BackGroundTask类中声明method属性。

编辑:像这样:

public class BackGroundTask extends AsyncTask<String, String, JSONObject>{
    List<NameValuePair> postparams= new ArrayList<NameValuePair>();
    String URL=null;
    String method = null;
public BackGroundTask(String url, String method, List<NameValuePair> params) {
        URL=url;
        postparams=params;
        this.method = method;
    }
    @Override
    protected JSONObject doInBackground(String... params) {
        // TODO Auto-generated method stub
        // Making HTTP request
        try {
    // Making HTTP request 
        // check for request method

    if(method.equals("POST")){
            // request method is POST
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(postparams));

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

        }else if(method == "GET"){
            // request method is GET
            DefaultHttpClient httpClient = new DefaultHttpClient();
            String paramString = URLEncodedUtils.format(postparams, "utf-8");
            url += "?" + paramString;
            HttpGet httpGet = new HttpGet(url);

            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();
        }           

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {

        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON String
    return jObj;

   }
 }
}

public BackGroundTask(String url, String method, List<NameValuePair> params) { URL=url; postparams=params; method=method; < like this? } - Twister
可选地,您可以将此参数传递给execute()方法。 - Patryk Dobrowolski
是的,没错。抱歉,在我写回答的时候你已经回答了。 - Patryk Dobrowolski
又需要帮助了.. 但我的代码有点长.. 怎么办?:'( - Twister
你知道如何使用 header 参数实现这个吗?谢谢。 - Jeongbebs
显示剩余3条评论

1

您需要在BackGroundTask类中将method设置为类变量。您将其传递到构造函数中,但没有对其进行任何操作。请按照与url和postparams相同的方式设置它。


在backgroundtask中应该在哪里设置它或将方法设置为类变量?我有点困惑。 - Twister

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接