programing

HttpClient로 본문 요청 작성

cafebook 2023. 10. 15. 17:54
반응형

HttpClient로 본문 요청 작성

XML content-type으로 요청 본문을 작성하려고 하는데 HttpClient Object( http://hc.apache.org/httpclient-3.x/apidocs/index.html )를 사용하는 방법을 모르겠습니다.

DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpRequest = new HttpPost(this.url);
httpRequest.setHeader("Content-Type", "application/xml");

그리고 XML로 본문을 계속 작성하는 방법을 모르겠습니다.

xml이 다음과 같이 작성된 경우java.lang.String그냥 사용하시면 됩니다.HttpClient이런 식으로

    public void post() throws Exception{
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost("http://www.baidu.com");
        String xml = "<xml>xxxx</xml>";
        HttpEntity entity = new ByteArrayEntity(xml.getBytes("UTF-8"));
        post.setEntity(entity);
        HttpResponse response = client.execute(post);
        String result = EntityUtils.toString(response.getEntity());
    }

예외에 주의를 기울입니다.

그건 그렇고, 예제는 httpclient version 4.x에 의해 작성되었습니다.

코드 확장(보낼 XML이 인 것으로 가정)xmlString) :

String xmlString = "</xml>";
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpRequest = new HttpPost(this.url);
httpRequest.setHeader("Content-Type", "application/xml");
StringEntity xmlEntity = new StringEntity(xmlString);
httpRequest.setEntity(xmlEntity );
HttpResponse httpresponse = httpclient.execute(httppost);

언급URL : https://stackoverflow.com/questions/18188041/write-in-body-request-with-httpclient

반응형