简体   繁体   English

Android http发布+ Web服务PHP

[英]Android http post + web service PHP

I have a web service in PHP which returns a String, he recives two parametres, id and te. 我在PHP中有一个返回字符串的Web服务,他引用了两个参数id和te。 I've tested its using with the mozzila addon poster, so i decided to use it for my android app. 我已经在mozzila插件海报上测试了它的使用,因此决定将其用于我的android应用程序。

This is my android code: 这是我的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");   
    }
});

I'm debugging whith log.i and i've could seen that it doesn't show neither recived neither fail. 我正在调试log.i,我已经看到它没有显示既没有记录也没有失败。 can anyone helpl me? 有人可以帮我吗?

PD: i leave the most relevant of webService 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); 

the solution of @jaimin works but the compiler says: Type mismatch: cannot convert from AsyncTask to String in (!) @jaimin的解决方案有效,但是编译器说:类型不匹配:无法在(!)中从AsyncTask转换为String

this is the code: 这是代码:

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;
}

Look at below code for posting data to php 查看下面的代码,将数据发布到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();

    }

for Http Post i'll suggest you to use AsyncTask<> which will run in separate thread from UI here is the code i am using since two months and its working fine 对于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;

}

for passing values you can create constructor like this. 为了传递值,您可以创建这样的构造函数。

form your activity do this 在您的活动中执行此操作

 HttpAsyncTask httpAsyncTask = new HttpAsyncTask(id,te);//this will pass variables values 
 String  ResultfromServer = httpAsyncTask.execute(urlStr);// String ResultfromServer is your response string

and in AsyncTask I've created constructor 在AsyncTask中我创建了构造函数

this is very helpful for me hope it will help you too 这对我很有帮助,希望对您也有帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM