0

Is there a way to extract HttpResponse from HttpClient() and GetMethod in java? I need the HttpEntity from the response using HttpClient. Anyone knows a way? My code :

client = new HttpClient();
GetMethod get = new GetMethod(URL);
        get.setDoAuthentication(true);
        try{

            int statusCode = client.executeMethod(get);
            //parsing XML from response
            //System.out.println(get.getResponseBodyAsString());
            if(statusCode == 200){
                System.out.println();
              // here I need HttpResponse object to get HttpEntity
            }


        }finally{
            get.releaseConnection();
        }
Itsik Mauyhas
  • 3,824
  • 14
  • 69
  • 114
  • Post your full code, and please do so quickly before your question gets voted down. – Tim Biegeleisen Nov 25 '15 at 09:37
  • May be this post will be helpful for you > http://stackoverflow.com/questions/5769717/how-can-i-get-an-http-response-body-as-a-string-in-java – newuserua_ext Nov 25 '15 at 09:41
  • No. As one client can process a number of requests and therefore deliver a number of responses, there is no direct relation between the client ant the data or requests respectively. You may access the body over the URLConnection object. Why are you limited to the HttpClient? – Hermann Klecker Nov 25 '15 at 09:44
  • due to Credentials. how can I access the body? – Itsik Mauyhas Nov 25 '15 at 09:53
  • Do you need to add credentials? That is a different question. You cannot add credentials to the body using GET. You will need to send a POST request then. When it is for HTTP basic auth then you could add credentials to the URL which I strongly discourage. (The URL is not crypted but the body is when using HTTPS.) – Hermann Klecker Nov 25 '15 at 09:57
  • I solved that. yes that works, thanks. – Itsik Mauyhas Nov 25 '15 at 10:43

1 Answers1

1
client = new HttpClient();
GetMethod get = new GetMethod(URL);
        get.setDoAuthentication(true);
        try{

            HttpResponse response = client.executeMethod(get);
            //parsing XML from response
            //System.out.println(get.getResponseBodyAsString());
            int statusCode = httpResponse.getStatusLine().getStatusCode();
            if(statusCode == 200){
                System.out.println();
              // here I need HttpResponse object to get HttpEntity
              BufferedReader buffer = new BufferedReader
                  (new InputStreamReader(response.getEntity().getContent()));
              String line = "";
              while ((line = buffer.readLine()) != null) {
                  textView.append(line);
              } 
            }
        } finally {
            get.releaseConnection();
        }
Hermann Klecker
  • 14,039
  • 5
  • 48
  • 71