如何从Web服务获取信息?

时间:2015-03-23 21:47:04

标签: php android web service

我需要从php web服务获取信息,但是当我在android中执行HttpPost时 应用程序在HttpResponse响应中断了jusrt响应= httpclient.execute(httppost);

这是我的Android代码

public String getHttp(){
    String jsonResult ="";
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://android.0fees.us/escuela.php");
    try {
        HttpResponse response = httpclient.execute(httppost);
          jsonResult = convertStreamtoString(
                response.getEntity().getContent()).toString();
    }
    catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return jsonResult;
}

private String convertStreamtoString(InputStream resultado) throws IOException{
    if(resultado != null){
        StringBuilder sb = new StringBuilder();
        String con = "";
        try{
            BufferedReader br = new BufferedReader(
                    new InputStreamReader(resultado, "UTF-8"));

            while((con = br.readLine())!= null){
                sb.append(con).append("'n");
            }

        }finally{
            resultado.close();
        }
        return sb.toString();
    }
    else{
        return "";
    }
}

这是我的PHP代码

<?php 
 include ('conex.php');
       $result = mysql_query("Select nombre FROM escuela") or die("No se realizo");
       $json = array();
        if(mysql_num_rows($result)){
              while ($row = mysql_fetch_assoc($result)) {
                   $json[]= $row;
               }
        }
        echo json_encode($json);
?>

我希望你能帮助我,谢谢你

1 个答案:

答案 0 :(得分:0)

感谢您帮助我。

我得解决它,我创建了一个允许我没有问题的新类,我只是扩展AsyncTask,并将我的代码放在doInBackground中:

public class HttpRequest extends AsyncTask {

@Override
protected String doInBackground(Object[] objects) {
    String jsonResult ="";
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://android.0fees.us/escuela.php");
    try {
        HttpResponse response = httpclient.execute(httppost);
        jsonResult = convertStreamtoString(
                response.getEntity().getContent()).toString();
    }
    catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    MainActivity.a = jsonResult;
    return jsonResult;
}

private String convertStreamtoString(InputStream resultado) throws IOException{
    if(resultado != null){
        StringBuilder sb = new StringBuilder();
        String con = "";
        try{
            BufferedReader br = new BufferedReader(
                    new InputStreamReader(resultado, "UTF-8"));

            while((con = br.readLine())!= null){
                sb.append(con).append("'n");
            }

        }finally{
            resultado.close();
        }
        return sb.toString();
    }
    else{
        return "";
    }
}

}