如何从AsyncTask http post获得结果?

时间:2014-05-30 05:59:58

标签: android android-asynctask

假设我有文本输入和输出以及要发布的按钮。所以,我将一些json(nameValuePairs)发布到给定的API。我知道如何通过Strict模式制作这个东西线程策略技巧,但是,我需要使用AsyncTask来使用ProgressBar。

public class MainActivity extends Activity  {
//Toast.makeText(getBaseContext(), str_text_input, Toast.LENGTH_LONG).show();
public String URL = "someurl";
EditText text_input;
EditText output;
ProgressBar progressbar;


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


    text_input = (EditText) findViewById(R.id.text_input);          
    output = (EditText) findViewById(R.id.text_output);


    progressbar = (ProgressBar) findViewById(R.id.progressBar);
    progressbar.setVisibility(View.GONE);

}

public void button_called(View view) {      
     progressbar.setVisibility(View.VISIBLE);
     String txt = text_input.getText().toString();

     sendPostRequest(txt, "somecheckcode", Integer.toString(int1), Integer.toString(int2));
     // Here I want result of posting http request = Response 


     output.setText(Response);   

}   

 String sendPostRequest(String txt, String Code, String dir, String topic ) {

    class SendPostReqAsyncTask extends AsyncTask<String, Void, String>{

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

            String text = params[0];
            String code = params[1];
            String direction = params[2];
            String topics = params[3];
            String finalResult = "";

            //System.out.println("*** doInBackground ** paramUsername " + paramUsername + " paramPassword :" + paramPassword);

            HttpClient httpClient = new DefaultHttpClient();

            // In a POST request, we don't pass the values in the URL.
            //Therefore we use only the web page URL as the parameter of the HttpPost argument
            HttpPost httpPost = new HttpPost(URL);

            // Because we are not passing values over the URL, we should have a mechanism to pass the values that can be
            //uniquely separate by the other end.
            //To achieve that we use BasicNameValuePair             
            //Things we need to pass with the POST request
            BasicNameValuePair srctxt = new BasicNameValuePair("param1", text);
            BasicNameValuePair chkcode = new BasicNameValuePair("param2", code);
            BasicNameValuePair direct = new BasicNameValuePair("param3", direction);
            BasicNameValuePair sbjbs = new BasicNameValuePair("param4", topics);

            // We add the content that we want to pass with the POST request to as name-value pairs
            //Now we put those sending details to an ArrayList with type safe of NameValuePair
            List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
            nameValuePairList.add(srctxt);
            nameValuePairList.add(chkcode);
            nameValuePairList.add(direct);
            nameValuePairList.add(sbjbs);

            try {
                // UrlEncodedFormEntity is an entity composed of a list of url-encoded pairs. 
                //This is typically useful while sending an HTTP POST request. 
                UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(nameValuePairList, HTTP.UTF_8);

                // setEntity() hands the entity (here it is urlEncodedFormEntity) to the request.
                httpPost.setEntity(urlEncodedFormEntity);

                try {
                    // HttpResponse is an interface just like HttpPost.
                    //Therefore we can't initialize them
                    HttpResponse httpResponse = httpClient.execute(httpPost);

                    // According to the JAVA API, InputStream constructor do nothing. 
                    //So we can't initialize InputStream although it is not an interface
                    InputStream inputStream = httpResponse.getEntity().getContent();

                    InputStreamReader inputStreamReader = new InputStreamReader(inputStream);

                    BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

                    StringBuilder stringBuilder = new StringBuilder();

                    String bufferedStrChunk = null;

                    while((bufferedStrChunk = bufferedReader.readLine()) != null){
                        stringBuilder.append(bufferedStrChunk);
                    }
                    finalResult = stringBuilder.toString();
                    return stringBuilder.toString();

                } catch (ClientProtocolException cpe) {
                    System.out.println("First Exception of HttpResponese :" + cpe);
                    cpe.printStackTrace();
                } catch (IOException ioe) {
                    System.out.println("Second Exception of HttpResponse :" + ioe);
                    ioe.printStackTrace();
                }

            } catch (UnsupportedEncodingException uee) {
                System.out.println("An Exception given because of UrlEncodedFormEntity argument :" + uee);
                uee.printStackTrace();
            }

            return finalResult;
        }

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


        }           
    }

    SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();

    sendPostReqAsyncTask.execute(txt, Code, dir, topic);
           return "RESULT_I_WANTED";
}

2 个答案:

答案 0 :(得分:1)

在activity中创建另一个方法来设置输出文本并获取输入字符串参数,如下所示。

public void setOutputText(String outputText) {

   output.setText(outputText);

 }

然后在AsyncTask的onPostExecute方法中调用此方法,如下所示。

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        setOutputText(result);

    }   

答案 1 :(得分:0)

public class MainActivity extends Activity {
//Toast.makeText(getBaseContext(), str_text_input, Toast.LENGTH_LONG).show();
public String URL = "someurl";
EditText text_input;
EditText output;
ProgressBar progressbar;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.user_interface);
    text_input = (EditText) findViewById(R.id.text_input);
    output = (EditText) findViewById(R.id.text_output);

    progressbar = (ProgressBar) findViewById(R.id.progressBar);
    progressbar.setVisibility(View.GONE);

}

public void button_called(View view) {
    progressbar.setVisibility(View.VISIBLE);
    String txt = text_input.getText().toString();

    //sendPostRequest(txt, "somecheckcode", Integer.toString(int1), Integer.toString(int2));
    // Here I want result of posting http request = Response 

    SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();

    sendPostReqAsyncTask.execute(txt, "somecheckcode", Integer.toString(int1), Integer.toString(int2));

}

void sendPostRequest(String response) {

    output.setText(response);
}

class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {

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

        String text = params[0];
        String code = params[1];
        String direction = params[2];
        String topics = params[3];
        String finalResult = "";

        //System.out.println("*** doInBackground ** paramUsername " + paramUsername + " paramPassword :" + paramPassword);

        HttpClient httpClient = new DefaultHttpClient();

        // In a POST request, we don't pass the values in the URL.
        //Therefore we use only the web page URL as the parameter of the HttpPost argument
        HttpPost httpPost = new HttpPost(URL);

        // Because we are not passing values over the URL, we should have a mechanism to pass the values that can be
        //uniquely separate by the other end.
        //To achieve that we use BasicNameValuePair             
        //Things we need to pass with the POST request
        BasicNameValuePair srctxt = new BasicNameValuePair("param1", text);
        BasicNameValuePair chkcode = new BasicNameValuePair("param2", code);
        BasicNameValuePair direct = new BasicNameValuePair("param3", direction);
        BasicNameValuePair sbjbs = new BasicNameValuePair("param4", topics);

        // We add the content that we want to pass with the POST request to as name-value pairs
        //Now we put those sending details to an ArrayList with type safe of NameValuePair
        List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
        nameValuePairList.add(srctxt);
        nameValuePairList.add(chkcode);
        nameValuePairList.add(direct);
        nameValuePairList.add(sbjbs);

        try {
            // UrlEncodedFormEntity is an entity composed of a list of url-encoded pairs. 
            //This is typically useful while sending an HTTP POST request. 
            UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(nameValuePairList, HTTP.UTF_8);

            // setEntity() hands the entity (here it is urlEncodedFormEntity) to the request.
            httpPost.setEntity(urlEncodedFormEntity);

            try {
                // HttpResponse is an interface just like HttpPost.
                //Therefore we can't initialize them
                HttpResponse httpResponse = httpClient.execute(httpPost);

                // According to the JAVA API, InputStream constructor do nothing. 
                //So we can't initialize InputStream although it is not an interface
                InputStream inputStream = httpResponse.getEntity().getContent();

                InputStreamReader inputStreamReader = new InputStreamReader(inputStream);

                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

                StringBuilder stringBuilder = new StringBuilder();

                String bufferedStrChunk = null;

                while ((bufferedStrChunk = bufferedReader.readLine()) != null) {
                    stringBuilder.append(bufferedStrChunk);
                }
                finalResult = stringBuilder.toString();
                return stringBuilder.toString();

            } catch (ClientProtocolException cpe) {
                System.out.println("First Exception of HttpResponese :" + cpe);
                cpe.printStackTrace();
            } catch (IOException ioe) {
                System.out.println("Second Exception of HttpResponse :" + ioe);
                ioe.printStackTrace();
            }

        } catch (UnsupportedEncodingException uee) {
            System.out.println("An Exception given because of UrlEncodedFormEntity argument :" + uee);
            uee.printStackTrace();
        }

        return finalResult;
    }

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

}