【问题标题】:Create an AsyncTask and put the code in doInBackground method [duplicate]创建一个 AsyncTask 并将代码放在 doInBackground 方法中[重复]
【发布时间】:2016-12-21 20:58:46
【问题描述】:

我找到了以下代码来执行 HTTP POST。它说我不直接在 UI/主线程中运行这些代码。创建一个 AsyncTask 并将代码放在 doInBackground 方法中。怎样才能让它在asynctask下运行。

String dataUrl = "http://example.com";
String dataUrlParameters = "email="+"pp@gmail.com"+"&name="+"priyabrat"+"&message="+"Message_here";
URL url;
HttpURLConnection connection = null;
try {
// Create connection
url = new URL(dataUrl);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length","" + Integer.toString(dataUrlParameters.getBytes().length));
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
// Send request
DataOutputStream wr = new DataOutputStream(
connection.getOutputStream());
wr.writeBytes(dataUrlParameters);
wr.flush();
wr.close();
// Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while ((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
String responseStr = response.toString();
Log.d("Server response",responseStr);

} catch (Exception e) {

e.printStackTrace();

} finally {

if (connection != null) {
connection.disconnect();
}
}

【问题讨论】:

  • 我编辑了我的答案。请看一下。

标签: android android-asynctask


【解决方案1】:

您可以尝试如下:

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

    mToolbar = (Toolbar) findViewById(R.id.toolbar);

    setSupportActionBar(mToolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setHomeButtonEnabled(true);


    String dataUrl = "http://example.com";
    String dataUrlParameters = "email="+"pp@gmail.com"+"&name="+"priyabrat"+"&message="+"Message_here";

    // Call background operation.
    new NetworkOperation().execute(dataUrl, dataUrlParameters);
}


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

    @Override
    protected String doInBackground(String... params) {
        String result = doNetworkOperation(params[0], params[1]);

        // more task if you have
        return result;
    }

    @Override
    protected void onPostExecute(String result) {

    }
}

private String doNetworkOperation(String dataUrl, String dataUrlParameters) {
    URL url;
    HttpURLConnection connection = null;
    String responseStr = "";
    try {
        // Create connection
        url = new URL(dataUrl);
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
        connection.setRequestProperty("Content-Length","" + Integer.toString(dataUrlParameters.getBytes().length));
        connection.setRequestProperty("Content-Language", "en-US");
        connection.setUseCaches(false);
        connection.setDoInput(true);
        connection.setDoOutput(true);
        // Send request
        DataOutputStream wr = new DataOutputStream(
        connection.getOutputStream());
        wr.writeBytes(dataUrlParameters);
        wr.flush();
        wr.close();
        // Get Response
        InputStream is = connection.getInputStream();
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        String line;
        StringBuffer response = new StringBuffer();
        while ((line = rd.readLine()) != null) {
            response.append(line);
            response.append('\r');
        }
        rd.close();
        responseStr = response.toString();
        Log.d("Server response",responseStr);

    } catch (Exception e) {

        e.printStackTrace();

    } finally {

        if (connection != null) {
            connection.disconnect();
        }
    }
    return responseStr;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-08
    • 2011-05-04
    • 1970-01-01
    • 2017-03-07
    • 1970-01-01
    • 2016-07-24
    相关资源
    最近更新 更多