[英]What is the best implementation of an HTTP client in Android to consume a web service
我有以下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();
}
}
}
}
}
我將其放在一個類中,並在其構造函數中設置所有內容,然后從活動中調用其方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.