[英]Android http post + web service PHP
我在PHP中有一個返回字符串的Web服務,他引用了兩個參數id和te。 我已經在mozzila插件海報上測試了它的使用,因此決定將其用於我的android應用程序。
這是我的android代碼:
final String query = null;
AsyncHttpClient client = new AsyncHttpClient();
RequestParams rp = new RequestParams();
rp.put("id", num);
rp.put("te", tab);
Log.i("http","before send\n");
client.post("http://appdomain.hol.es/webService.php",rp, new JsonHttpResponseHandler(){
public void onSuccess(String jObject)
{
query.replace(query, jObject);
Log.i("http","recived: "+jObject+"\n");
}
public void onFailure(Throwable arg0)
{
Log.i("http","fail");
}
});
我正在調試log.i,我已經看到它沒有顯示既沒有記錄也沒有失敗。 有人可以幫我嗎?
PD:我離開了最相關的webService
$id = $_POST["id"];
$te = $_POST["te"];
$query = "SELECT `preg` , `respA` , `respB` , `respC` , `respD` , `respV`FROM `".$te."` WHERE `id` =".$id;
$resultado= mysql_query($query,$link);
$arraySalida = array();
while($registro = mysql_fetch_assoc ($resultado) ):
$cadena = "{$registro['preg']};{$registro['respA']};{$registro['respB']};{$registro['respC']};{$registro['respD']};{$registro['respV']}";
$arraySalida[]= $cadena;
endwhile;
echo implode(":",$arraySalida);
@jaimin的解決方案有效,但是編譯器說:類型不匹配:無法在(!)中從AsyncTask轉換為String
這是代碼:
public String BBDD(int num, String tab)
{
HttpAsyncTask httpAsyncTask = new HttpAsyncTask(String.valueOf(num),tab);
/*(!)*/String resul = httpAsyncTask.execute("http://opofire.hol.es/webServiceOpoFire.php");
return resul;
}
查看下面的代碼,將數據發布到php
class PlaceOrder extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPst = new HttpPost(
"http://appdomain.hol.es/webService.php");
ArrayList<NameValuePair> parameters = new ArrayList<NameValuePair>(
2);
// add ur parameter here
parameters.add(new BasicNameValuePair("id", value1);
parameters.add(new BasicNameValuePair("te", value2);
httpPst.setEntity(new UrlEncodedFormEntity(parameters));
HttpResponse httpRes = httpClient.execute(httpPst);
String str=convertStreamToString(httpRes.getEntity().getContent()).toString();
Log.i("mlog","outfromurl"+str);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
public static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
對於Http Post,我建議您使用AsyncTask <>,它將在與UI分開的線程中運行,這是我兩個月以來一直在使用的代碼,並且工作正常
private class HttpAsyncTask extends AsyncTask<String, Void, String> {
private String id,te;
public HttpAsyncTask(String id,String te){
this.id = id;
this.te = te;
}
@Override
protected String doInBackground(String... urls) {
return POST(urls[0]);
}
// onPostExecute displays the results of the AsyncTask.
@Override
protected void onPostExecute(String result) {
Toast.makeText(getBaseContext(), "Data Sent!", Toast.LENGTH_LONG).show();
}
}
public static String POST(String url){
InputStream inputStream = null;
String result = "";
try {
// 1. create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// 2. make POST request to the given URL
HttpPost httpPost = new HttpPost(url);
// pass parameters in this way
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "value "));
nameValuePairs.add(new BasicNameValuePair("te", "value"));
//add data
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// 8. Execute POST request to the given URL
HttpResponse httpResponse = httpclient.execute(httpPost);
// 9. receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
// 10. convert inputstream to string
if(inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
// 11. return result
return result;
}
private static String convertInputStreamToString(InputStream inputStream) throws IOException {
// TODO Auto-generated method stub
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
String line = "";
String result = "";
while((line = bufferedReader.readLine()) != null)
result += line;
inputStream.close();
return result;
}
為了傳遞值,您可以創建這樣的構造函數。
在您的活動中執行此操作
HttpAsyncTask httpAsyncTask = new HttpAsyncTask(id,te);//this will pass variables values
String ResultfromServer = httpAsyncTask.execute(urlStr);// String ResultfromServer is your response string
在AsyncTask中我創建了構造函數
這對我很有幫助,希望對您也有幫助
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.