本文介绍了Android的HTTP POST + Web服务PHP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在PHP返回一个字符串的Web服务,他收到
2参数应用,身份证和Te。
我测试过它与mozzila插件使用的海报,所以我决定用它为我的Andr​​oid应用。

这是我的Andr​​oid code:

 最后的查询字符串= NULL;AsyncHttpClient客户端=新AsyncHttpClient();
RequestParams RP =新RequestParams();
rp.put(ID,NUM);
rp.put(TE,标签);
Log.i(HTTP,送之前\\ n);
client.post(http://appdomain.hol.es/webService.php,RP,新JsonHtt presponseHandler(){    公共无效的onSuccess(字符串jObject)
    {
        query.replace(查询,jObject);
Log.i(HTTP,recived:+ jObject +\\ n);    }
    公共无效onFailure处(Throwable的为arg0)
    {
Log.i(HTTP,失败);
    }
});

我调试蒙山log.i,我已经可以看到,它并不显示既不recived没有失败。
任何人都可以helpl我?

PD:我留下最相关的WebService

 的$ id = $ _ POST [ID];
$ TE = $ _ POST [TE];
$查询=SELECT`preg`,`respA`​​,`respB`,`respC`,`respD`,``respV`FROM$忒`其中`id` =$ ID。;$ resultado =的mysql_query($查询,$链接);
$ arraySalida =阵列();
而($ registro = mysql_fetch_assoc($ resultado)):
    $卡德纳= \"{$registro['$p$pg']};{$registro['respA']};{$registro['respB']};{$registro['respC']};{$registro['respD']};{$registro['respV']}\";
    $ arraySalida [] = $卡德纳;ENDWHILE;
回声破灭(:,$ arraySalida);

@jaimin作品的解决办法,但编译器说:类型不匹配:不能从AsyncTask的转换为字符串在

(!)

这是code:

 公共字符串BBDD(INT NUM,串片)
    {
        HttpAsyncTask httpAsyncTask =新HttpAsyncTask(将String.valueOf(NUM)选项卡);
        (!)/ * * /字符串resul = httpAsyncTask.execute(http://opofire.hol.es/webServiceOpoFire.php);        返回resul;
}


解决方案

有关HTTP POST我会建议你使用的AsyncTask<>将在用户界面上单独的线程中运行
这里是code两个月以来我使用和它的做工精细

 私有类HttpAsyncTask扩展的AsyncTask<弦乐,太虚,字符串> {
 私人字符串ID,忒;
 公共HttpAsyncTask(ID字符串,字符串TE){
        this.id = ID;
        this.te = TE;    }        @覆盖
        保护字符串doInBackground(字符串的URL ...){            返回POST(网址[0]);
        }
        // onPostExecute显示的AsyncTask的结果。
        @覆盖
        保护无效onPostExecute(字符串结果){
            Toast.makeText(getBaseContext(),发送的数据!,Toast.LENGTH_LONG).show();
       }
    }
公共静态字符串POST(字符串URL){
    为InputStream的InputStream = NULL;
    字符串结果=;
    尝试{        // 1.创建HttpClient的
        HttpClient的HttpClient的=新DefaultHttpClient();        // 2.化妆POST请求到指定的URL
        HttpPost httpPost =新HttpPost(URL);
       以这种方式//传递参数       清单<&的NameValuePair GT; namevaluepairs中=新的ArrayList<&的NameValuePair GT;(2);
    nameValuePairs.add(新BasicNameValuePair(ID,价值));
    nameValuePairs.add(新BasicNameValuePair(TE,价值));    //添加数据
    httppost.setEntity(新UrlEn codedFormEntity(namevaluepairs中));        // 8.执行POST请求到指定的URL
        HTT presponse HTT presponse = httpclient.execute(httpPost);        // 9.收到响应为InputStream的
        的InputStream = HTT presponse.getEntity()的getContent()。        // 10.转换的InputStream串
        如果(的InputStream!= NULL)
            结果= convertInputStreamToString(InputStream的);
        其他
            结果=没有工作!    }赶上(例外五){
        Log.d(InputStream的,e.getLocalizedMessage());
    }
 // 11返回结果
    返回结果;}私人静态字符串convertInputStreamToString(的InputStream的InputStream)抛出IOException
    // TODO自动生成方法存根    的BufferedReader的BufferedReader =新的BufferedReader(新的InputStreamReader(InputStream的));
    串线=;
    字符串结果=;
    而((行= bufferedReader.readLine())!= NULL)
        结果+ =行;    inputStream.close();
    返回结果;}

传递值,您可以创建构造这样。

形成你的活动做到这一点。

  HttpAsyncTask httpAsyncTask =新HttpAsyncTask(ID,TE); //这会传递变量的值
 字符串ResultfromServer = httpAsyncTask.execute(urlStr); //字符串ResultfromServer是你的响应字符串

和中的AsyncTask我已经创建构造

这是非常有帮助,我希望它会帮助你太

I have a web service in PHP which returns a String, he recives two parametres, id and te.I've tested its using with the mozzila addon poster, so i decided to use it for my android app.

This is my android code:

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.can anyone helpl me?

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

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;
}
解决方案

for Http Post i'll suggest you to use AsyncTask<> which will run in separate thread from UIhere is the code i am using since two months and its working fine

 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

this is very helpful for me hope it will help you too

这篇关于Android的HTTP POST + Web服务PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 18:05