HttpRequest 와 함께 비동기 를 사용하여 PHP 페이지에 값을 보내고 응답을 얻은 다음 OnPostExcute 를 사용하여 무언가를 수행하는 방법 .
자바 :
private class MyAsyncTask extends AsyncTask<String, Integer, Double>{
@Override
protected Double doInBackground(String... params) {
// TODO Auto-generated method stub
postData(params[0]);
return null;
}
protected void onPostExecute(Double result){
pb.setVisibility(View.GONE);
// Do something with the response here
// ....
}
public void postData(String valueIWantToSend) {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("__url_to_file.php");
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("myHttpData", valueIWantToSend));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
}
}
PHP :
<?php
// return the value back to the app
echo $_POST["myHttpData"];
?>
private class MyAsyncTask extends AsyncTask<String, HttpResponse, HttpResponse>{
@Override
protected HttpResponse doInBackground(String... params) {
// TODO Auto-generated method stub
return postData(params[0]);
}
protected void onPostExecute(HttpResponse result){
View pb;
pb.setVisibility(View.GONE);
HttpEntity entity = result.getEntity();
String responseString = EntityUtils.toString(entity, "UTF-8");
Toast.makeText(mContext, responseString, Toast.LENGTH_LONG).show();
}
@SuppressWarnings("unchecked")
public HttpResponse postData(String valueIWantToSend) {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("__url_to_file.php");
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("myHttpData", valueIWantToSend));
httppost.setEntity(new UrlEncodedFormEntity((List<? extends org.apache.http.NameValuePair>) nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
return response;
}
}
위의 방법으로 뭔가를 할 수 있습니다. 그것은 확실히 HttpResponse를 onPostExecute 메소드에 전달하고 그것으로 무언가를 할 수있게합니다.
그래도이 줄을 살펴 보겠습니다.
httppost.setEntity(new UrlEncodedFormEntity((List<? extends org.apache.http.NameValuePair>) nameValuePairs));
나에게 옳지 않은 것처럼 보였습니다. 컴파일러를 행복하게 만들기 위해 캐스트를 추가해야했습니다. 원하는 결과가 아닐 수도 있습니다 (그러나 HttpResponse를 처리 할 수 있도록 ASyncTask를 얻는 데는 시간이 낭비되었습니다).
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다