Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/225.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 如何从AsyncTask http post获取结果?_Android_Android Asynctask - Fatal编程技术网

Android 如何从AsyncTask http post获取结果?

Android 如何从AsyncTask http post获取结果?,android,android-asynctask,Android,Android Asynctask,假设我有文本输入和输出以及要发布的按钮。因此,我将一些json(nameValuePairs)发布到给定的API中。我知道如何通过严格模式线程策略技巧来实现这一点,但是,我需要AsyncTask来使用ProgressBar public class MainActivity extends Activity { //Toast.makeText(getBaseContext(), str_text_input, Toast.LENGTH_LONG).show(); public String

假设我有文本输入和输出以及要发布的按钮。因此,我将一些json(nameValuePairs)发布到给定的API中。我知道如何通过严格模式线程策略技巧来实现这一点,但是,我需要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";
}
公共类MainActivity扩展活动{
//Toast.makeText(getBaseContext(),str_text_input,Toast.LENGTH_LONG).show();
公共字符串URL=“someurl”;
编辑文本输入;
编辑文本输出;
ProgressBar ProgressBar;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.user\u界面);
text\u input=(EditText)findViewById(R.id.text\u input);
输出=(EditText)findViewById(R.id.text\u输出);
progressbar=(progressbar)findViewById(R.id.progressbar);
progressbar.setVisibility(View.GONE);
}
公共无效按钮_调用(视图){
progressbar.setVisibility(View.VISIBLE);
String txt=text_input.getText().toString();
sendPostRequest(txt,“somecheckcode”、Integer.toString(int1)、Integer.toString(int2));
//这里我想要发布http请求=响应的结果
output.setText(响应);
}   
字符串sendPostRequest(字符串txt、字符串代码、字符串目录、字符串主题){
类SendPostReqAsyncTask扩展了AsyncTask{
@凌驾
受保护的字符串doInBackground(字符串…参数){
字符串文本=参数[0];
字符串代码=参数[1];
字符串方向=参数[2];
字符串主题=参数[3];
字符串finalResult=“”;
//System.out.println(“***doInBackground**paramUsername”+paramUsername+“paramPassword:+paramPassword”);
HttpClient HttpClient=新的DefaultHttpClient();
//在POST请求中,我们不传递URL中的值。
//因此,我们只使用网页URL作为HttpPost参数的参数
HttpPost HttpPost=新的HttpPost(URL);
//因为我们没有通过URL传递值,所以我们应该有一种机制来传递可以传递的值
//被另一端唯一地分开。
//为了实现这一点,我们使用BasicNameValuePair
//我们需要通过POST请求传递的内容
BasicNameValuePair srctxt=新的BasicNameValuePair(“参数1”,文本);
BasicNameValuePair chkcode=新的BasicNameValuePair(“参数2”,代码);
BasicNameValuePair direct=新的BasicNameValuePair(“参数3”,方向);
BasicNameValuePair sbjbs=新的BasicNameValuePair(“参数4”,主题);
//我们将希望与POST请求一起传递的内容添加为名称-值对
//现在,我们将那些发送详细信息的内容放在类型安全的NameValuePair的ArrayList中
List nameValuePairList=新的ArrayList();
nameValuePairList.add(srctxt);
nameValuePairList.add(chkcode);
nameValuePairList.add(直接);
nameValuePairList.add(sbjbs);
试一试{
//UrlEncodedFormEntity是由url编码对列表组成的实体。
//这在发送HTTP POST请求时通常很有用。
UrlEncodedFormEntity UrlEncodedFormEntity=新的UrlEncodedFormEntity(nameValuePairList,HTTP.UTF_8);
//setEntity()将实体(这里是urlEncodedFormEntity)交给请求。
setEntity(urlEncodedFormEntity);
试一试{
//HttpResponse是一个与HttpPost类似的接口。
//因此,我们无法初始化它们
HttpResponse HttpResponse=httpClient.execute(httpPost);
//根据JavaAPI,InputStream构造函数什么都不做。
//所以我们不能初始化InputStream,尽管它不是一个接口
InputStream InputStream=httpResponse.getEntity().getContent();
InputStreamReader InputStreamReader=新的InputStreamReader(inputStream);
BufferedReader BufferedReader=新的BufferedReader(inputStreamReader);
StringBuilder StringBuilder=新的StringBuilder();
字符串bufferedStrChunk=null;
while((bufferedStrChunk=bufferedReader.readLine())!=null){
追加(bufferedStrChunk);
}
finalResult=stringBuilder.toString();
返回stringBuilder.toString();
}捕获(客户端协议异常cpe){
System.out.println(“HttpResponse的第一个例外:“+cpe”);
printStackTrace();
}捕获(ioe异常ioe){
System.out.println(“HttpResponse的第二个例外:“+ioe”);
ioe.printStackTrace();
}
}捕获(不支持的编码异常uee){
System.out.println(“由于UrlEncodedFormEntity参数:“+uee”而给出的异常);
uee.printStackTrace();
}
返回最终结果;
}
@凌驾
受保护的void onPostExecute(字符串结果){
super.onPostExecute(结果);
}           
}
SendPostReqAsyncTask SendPostReqAsyncTask=新建SendPostReqAsyncTask();
执行(txt,代码,目录,主题);
返回“我想要的结果”;
}

在“活动”中创建另一个方法,以设置输出文本并获取输入字符串参数,如下所示

public void setOutputText(String outputText) {

   output.setText(outputText);

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

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

public void setOutputText(String outputText) {

   output.setText(outputText);

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

    }   
公共类MainActivity扩展活动{
//Toast.makeText(getBaseContext(),str_text_input,Toast.LENGTH_LONG).show();
公共字符串URL=“someurl”;
编辑文本输入;
编辑文本输出;
ProgressBar ProgressBar;
@凌驾
赞成的意见