How to get only string from HTTPResponse RestApi A

2019-08-12 07:36发布

问题:

I have tried this code snippet to get the response from android using HTTPResponse

String s="";
try {

    HttpClient httpClient=new DefaultHttpClient();
    HttpPost httpPost=new HttpPost("http://10.0.0.8:7777/HttpPostServlet/servlet/Login");
    List<NameValuePair> list=new ArrayList<NameValuePair>();
    list.add(new BasicNameValuePair("uname", valuse[0]));
    list.add(new BasicNameValuePair("pwd",valuse[1]));
    httpPost.setEntity(new UrlEncodedFormEntity(list));
    HttpResponse httpResponse=  httpClient.execute(httpPost);
    HttpEntity httpEntity=httpResponse.getEntity();
    String responseStr = EntityUtils.toString(httpResponse.getEntity());
    s= readResponse(httpResponse);
    System.err.println("Response: " + s +"/// "+ "another resposn :: "+responseStr );
} catch(Exception exception)    {

    System.err.println("Exception: " + exception.getMessage());
}

also i have tried this another method to get reponse

public String readResponse(HttpResponse res) {

    InputStream is=null;
    String return_text="";
    String result="";
    try {

        is=res.getEntity().getContent();
        BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(is));
        String line="";
        StringBuffer sb=new StringBuffer();
        HttpEntity entity = res.getEntity();
        while ((line=bufferedReader.readLine())!=null) {

            sb.append(line);
        }
        return_text=sb.toString();
        result = EntityUtils.toString(entity).toString();
    } catch (Exception e) {}
    return result;
}

I am getting response as follows

<?xml version="1.0" encoding="utf-8"?><string xmlns="http://23.253.164.20:8096/">Unsuccessfull</string>

I want only unsuccessfull or successful

Do i have to change in server side or it could be done client side to get plain text

回答1:

What you need is one more line - when you become the HttpResponse it is the whole html from the response site, so you need to remove all tags from it and you could do this with a single line String responseAsText = android.text.Html.fromHtml(result).toString() where result is your string with the repsonse from the Httpresponse. You can add this line at the end of both codes you have provided.