2013-05-30 3 views
0

Я пытаюсь реплицировать следующий код C# в Java. Этот код является вспомогательным классом, который отправляет запрос, содержащий xml, и считывает ответ.Отправка xml с использованием Apache HttpComponents

internal static String Send(String url, String body) 
    { 
     HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url); 
     try 
     { 
      // create the new httpwebrequest with the uri 
      request.ContentLength = 0; 
      // set the method to POST 
      request.Method = "POST"; 

      if (!String.IsNullOrEmpty(body)) 
      { 
       request.ContentType = "application/xml; charset=utf-8"; 
       byte[] postData = Encoding.Default.GetBytes(body); 
       request.ContentLength = postData.Length; 
       using (Stream s = request.GetRequestStream()) 
       { 
        s.Write(postData, 0, postData.Length); 
       } 

      } 

      using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) 
      { 
       String responseString = new StreamReader(response.GetResponseStream()).ReadToEnd(); 
       if (response.StatusCode != HttpStatusCode.OK) 
       { 
        throw new ResponseException(((int)response.StatusCode), 
         response.StatusCode.ToString(), request.RequestUri.ToString(), 
         responseString); 
       } 
       return responseString; 
      } 
     } 
     catch (WebException e) 
     { 
      using (WebResponse response = e.Response) 
      { 
       HttpWebResponse httpResponse = response as HttpWebResponse; 
       if (httpResponse != null) 
       { 
        using (Stream data = response.GetResponseStream()) 
        { 
         data.Position = 0; 
         throw new ResponseException(((int)httpResponse.StatusCode), 
           httpResponse.StatusCode.ToString(), request.RequestUri.ToString(), 
           new StreamReader(data).ReadToEnd() 
          ); 
        } 
       } 
       else 
       { 
        throw; 
       } 

После прочтения других тема, я решил, что библиотека Apache HttpComponents будет моим лучшим выбором, чтобы получить ту же функциональность. После прочтения документации и следуя примеру здесь:

http://hc.apache.org/httpcomponents-client-ga/quickstart.html

Я не могу понять, как отправить строку тела, как XML. Когда я пытаюсь установить объект для запроса, ему требуется объявить BasicNameValuePair, и я не понимаю, что это такое, или как я буду форматировать строку тела для соответствия этой спецификации. Ниже приведено то, что я сделал в настоящее время.

protected static String Send(String url, String body) 
{ 
    HttpPost request = new HttpPost(url); 

    try 
    { 
     request.setHeader("ContentType", "application/xml; charset=utf=8"); 

     // Encode the body if needed 
     request.setEntity(new UrlEncodedFormEntity()); 

     //get the response 

     // if the response code is not valid throw a ResponseException 

     // else return the response string. 

    } finally { 
     request.releaseConnection(); 
    } 
    return null; 
} 

EDIT: или я должен использовать StringEntity и сделайте следующее

protected static String SendToJetstream(String url, String body) 
{ 
    HttpPost request = new HttpPost(url); 

    try 
    { 
     StringEntity myEntity = new StringEntity(body, 
       ContentType.create("application/xml", "UTF-8")); 


     // Encode the body if needed 
     request.setEntity(myEntity); 

     //get the response 

     // if the response code is not valid throw a ResponseException 

     // else return the response string. 

    } finally { 
     request.releaseConnection(); 
    } 
    return null; 
} 

ответ

0

Используйте FileEntity

File file = new File("somefile.xml"); 
FileEntity entity = new FileEntity(file, ContentType.create("application/xml", "UTF-8")); 

Много хороших примеров здесь: http://hc.apache.org/httpcomponents-client-ga/tutorial/html/fundamentals.html#d5e165

+0

Поскольку мой xml в настоящее время передается как строка, это мое редактирование с использованием StringEntity лучше? – JME

+0

В таком случае, да. – Keith

Смежные вопросы