从AsyncTask Android返回JSON字符串

时间:2014-09-17 09:14:36

标签: android json android-asynctask

通常我会为每个使用 AsyncTask 扩展的Web服务调用创建类,并且很难维护代码。所以我想创建One类并根据参数获取OUTPUT Json字符串。 如何返回JSON字符串?

更新

这是我试过的

public class WebCallController extends AsyncTask<Void,Void,String>
 {
String PassPeram = "";
JSONStringer JSonRequestString;
String URL;
String JSonResponseString;

public WebCallController(String PerameterPass, JSONStringer JSonRequestString, String URL) {
    PassPeram = PerameterPass;
    this.JSonRequestString = JSonRequestString;
    this.URL = URL;
}

@Override
protected void onPreExecute() {
    super.onPreExecute();
}

@Override
protected String doInBackground(Void... params) {

    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(URL);
    post.setHeader("Content-type", "application/json");

    try {
        StringEntity entity = new StringEntity(JSonRequestString.toString());
        post.setEntity(entity);
    }
    catch (Exception Ex)
    {

    }


    try {
        HttpResponse response = client.execute(post);
        StatusLine status = response.getStatusLine();
        int statusCode = status.getStatusCode();

        if(statusCode == 400)
        {
            Log.d("Error", "bad request");
        }
        else if(statusCode == 505)
        {
            Log.d("Error","Internal server error");
        }
        else
        {
            InputStream jsonStream = response.getEntity().getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(jsonStream));

            StringBuilder builder = new StringBuilder();
            String line;

            while((line = reader.readLine()) != null)
            {
                builder.append(line);
            }

            JSonResponseString = builder.toString();

        }
    }
    catch (IOException Ex)
    {

    }
    return JSonResponseString;
}

@Override
protected void onPostExecute(String aVoid) {
    super.onPostExecute(aVoid);
}

}

4 个答案:

答案 0 :(得分:2)

这可能就是你要找的东西(获取字符串作为结果并将其解析为json):

  YourAsycTask yat=new YourAsycTask();

yat.execute();

String result=yat.get().toString();

答案 1 :(得分:2)

尝试下面的代码并将其放在单独的类中,从而将json字符串返回到您的活动。

只将您的网址传递给此方法并以字符串形式获取响应。

 public static final String GetConnectionInputStream(String strUrl) {
    String line = null;
    String response = null;
    try {

        HttpParams httpParameters = new BasicHttpParams();
        // Set the timeout in milliseconds until a connection is
        // established.
        // The default value is zero, that means the timeout is not used.
        HttpConnectionParams.setConnectionTimeout(httpParameters, 30000);
        // Set the default socket timeout (SO_TIMEOUT)
        // in milliseconds which is the timeout for waiting for data.
        HttpConnectionParams.setSoTimeout(httpParameters, 30000);
        // This is the default apacheconnection.
        HttpClient mHttpClient = new DefaultHttpClient(httpParameters);

        // Pathe of serverside
        HttpGet mHttpGet = new HttpGet(strUrl);

        // get the valu from the saerverside as response.
        HttpResponse mHttpResponse = mHttpClient.execute(mHttpGet);
        HttpEntity mHttpEntity = mHttpResponse.getEntity();

        try {
            // convert response in to the string.
            if (mHttpEntity.getContent() != null) {
                BufferedReader mBufferedReader = new BufferedReader(
                        new InputStreamReader(mHttpEntity.getContent(),
                                HTTP.UTF_8), 8);
                StringBuilder mStringBuilder = new StringBuilder();
                while ((line = mBufferedReader.readLine()) != null) {
                    mStringBuilder.append(line + "\n");
                }
                response = mStringBuilder.toString();

                // mInputStream.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
    return response;
}

更改您的doInBackground方法,如下所示:

private class GetParsedResponse extends AsyncTask<String, Void, String> {

    @Override
    protected void onPreExecute() {
     }

    @Override
    protected String doInBackground(Void... params) {

         String response=null;
          response=GetConnectionInputStream(URL);

         return response;
    }
    @Override
    protected void onPostExecute(String result) {

        //your response parsing code.
    }
}

答案 2 :(得分:2)

我假设您需要编写一个AsyncTask,它可以重复用于每个Web服务调用。您可以执行以下示例,

步骤1:创建abstract class

public abstract class HttpHandler {

    public abstract HttpUriRequest getHttpRequestMethod();

    public abstract void onResponse(String result);

    public void execute(){
        new AsyncHttpTask(this).execute();
    } 
}

<强> 2。 Sterp-2:写下您的AsyncTask代码

public class AsyncHttpTask extends AsyncTask<String, Void, String>{

    private HttpHandler httpHandler;
    public AsyncHttpTask(HttpHandler httpHandler){
        this.httpHandler = httpHandler;
    }

    @Override
    protected String doInBackground(String... arg0) {
       //do your task and return the result
        String result = "";


        return result;
    }
    @Override
    protected void onPostExecute(String result) {
        httpHandler.onResponse(result); // set it to the onResponse()
    }


}

第3步:编写Activity代码

public class MainActivity extends Activity implements OnClickListener {

    private Button btnRequest;
    private EditText etResponse;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btnRequest = (Button) findViewById(R.id.btnRequest);
        etResponse = (EditText) findViewById(R.id.etRespose);

         //check isConnected()...code is on github
        btnRequest.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {

        new HttpHandler() {
            @Override
            public HttpUriRequest getHttpRequestMethod() {

                return new HttpGet("http://hmkcode.com/examples/index.php");

                // return new HttpPost(url)
            }
            @Override
            public void onResponse(String result) {
                Toast.makeText(getBaseContext(), "Received!", Toast.LENGTH_LONG).show();
                etResponse.setText(result);
            }

        }.execute();
    }
    // public boolean isConnected(){}
  }

参考 http://hmkcode.com/android-cleaner-http-asynctask/

https://github.com/hmkcode/Android/tree/master/android-clean-http-async-task

答案 3 :(得分:1)

private class MyAsyncTask extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... params) {

        return "Executed";
    }

    @Override
    protected String onPostExecute(String result) {

        return "json String";
    }

    @Override
    protected void onPreExecute() {}

    @Override
    protected void onProgressUpdate(Void... values) {}
}