如何从类HTTPResponse RESTAPI的Android只得到字符串(How to get

2019-10-22 21:07发布

我曾尝试此代码段得到利用Android的响应类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());
}

我也有试过这种以其他方式取得效应初探

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

我得到的反应如下

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

我想只有unsuccessfull或成功

我必须在服务器端更改或它可以做客户端获得纯文本

Answer 1:

你需要的是一个更行-当你成为的HttpResponse是从响应网站的整个HTML,所以你需要删除所有的标签,你可以用一条线做这个String responseAsText = android.text.Html.fromHtml(result).toString()其中, result是你的字符串从HttpResponse对象的repsonse。 您可以在您所提供的两个代码的末尾添加这一行。



文章来源: How to get only string from HTTPResponse RestApi Android