我有以下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();
}
}
}
}
}
答案 0 :(得分:0)
我会将它放在一个类中,并在其构造函数中设置所有内容,并从活动中调用其方法。