0

我有以下 RESTful 代码,它可以访问此 Web 服务并发布一个值并获得回报。该代码有效,但是正如您所见,它位于 onCreate() 方法的 MainActivity 中。我不必详细说明这是一种不好的做法。那么,为了让应用程序具有最佳性能并且不会崩溃,我应该怎么做才能放置此代码。我想我正在寻找类似于设计模式的东西,以便使用 HTTPClient 来实现最强大的应用程序来使用 Web 服务。谢谢

http://www.w3schools.com/webservices/tempconvert.asmx/CelsiusToFahrenheit

public class MainActivity extends Activity {
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);

    BufferedReader in = null;
    try {
        HttpClient client = new DefaultHttpClient();
        HttpPost request = new HttpPost(
                "http://www.w3schools.com/webservices/tempconvert.asmx/CelsiusToFahrenheit");
        request.addHeader("Content-Type", "application/x-www-form-urlencoded");
        List<NameValuePair> postParameters = new ArrayList<NameValuePair>();
        postParameters.add(new BasicNameValuePair("Celsius", "77"));
        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
        request.setEntity(formEntity);

        HttpResponse response = client.execute(request);

        in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        StringBuffer sb = new StringBuffer("");
        String line = "";
        String NL = System.getProperty("line.separator");
        while ((line = in.readLine()) != null) {
            sb.append(line + NL);
        }
        in.close();

        String page = sb.toString();
        // Log.i(tag, page);
        System.out.println(page);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

}

4

1 回答 1

0

我会将它放在一个类中并在其构造函数中设置所有内容并从活动中调用其方法。

于 2012-09-09T20:46:58.387 回答