如何通过Java代码发送XML PUT请求

时间:2017-04-18 05:23:21

标签: java xml web-services http soap

我的项目上有一个REST Web服务。 我尝试使用Restlet Client(Google Chrome扩展程序)发送XML PUT请求。 我获得了200 OK的成功。 现在我想将相同的XML PUT请求发送到Web服务,但是通过JAVA CODE。

第一个解决方案: 我使用了Apache的HttpClient,但它返回org.apache.http.NoHttpResponseException:无法响应

import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;

public class Start {

public static void main(String[] args) throws IOException {

    String url = "SECRET";

    //CONFIGS
    String ip = "127.0.0.1";
    HttpHost proxy = new HttpHost(ip, 1080);
    HttpClient client = HttpClientBuilder.create().build();
    RequestConfig config = RequestConfig.custom().setProxy(proxy).build();
    HttpPut put = new HttpPut(url);
    put.setConfig(config);

    //HEADER SECTION
    put.setHeader("SourceApplication","application");
    put.setHeader("Content-Type", "application/xml");

    //BODY SECTION
    ArrayList<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
    urlParameters.add(new BasicNameValuePair("company","VALUE1"));
    urlParameters.add(new BasicNameValuePair("company2","VALUE2"));
    urlParameters.add(new BasicNameValuePair("company3","VALUE3"));
    urlParameters.add(new BasicNameValuePair("company4","VALUE4"));
    urlParameters.add(new BasicNameValuePair("company5","VALUE5"));
    urlParameters.add(new BasicNameValuePair("company6","VALUE6"));

    put.setEntity(new UrlEncodedFormEntity(urlParameters));


    //PRINT REQUEST
    String uri = put.getRequestLine().getUri();
    System.out.println(uri);
    BufferedReader bd = new BufferedReader(
            new InputStreamReader(put.getEntity().getContent()));
    StringBuffer rs = new StringBuffer();
    String line = "";
    while ((line = bd.readLine()) != null) {
        rs.append(line);
        System.out.println(line);
    }

    //EXECUTE REQUEST
    HttpResponse response = client.execute(put);
    System.out.println("Response Code : "
    + response.getStatusLine().getStatusCode());

    //PRINT RESPONSE
    BufferedReader bufferedReader = new BufferedReader(
            new InputStreamReader(response.getEntity().getContent()));

    StringBuffer result = new StringBuffer();
    String line1 = "";
    while ((line1 = bufferedReader.readLine()) != null) {
        result.append(line1);
        System.out.println(line1);
    }
}

}

RESPONSE

org.apache.http.NoHttpResponseException: failed to respond

第二个解决方案: 我试着用SOAP。 但是SOAP允许只发送GET和POST方法。(我需要发送PUT方法)。 当我通过POST方法发送我的xml时。响应返回405方法不允许。

public class CompanyCreationScript {

public static void main(String[] args) {
    try {
        SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
        SOAPConnection soapConnection = soapConnectionFactory.createConnection();

        System.setProperty("socksProxyHost", "127.0.0.1");
        System.setProperty("socksProxyPort", "1080");

        String url = "SECRET";
        SOAPMessage soapResponse = soapConnection.call(createSOAPRequest(), url);

        printSOAPResponse(soapResponse);

        soapConnection.close();
    } catch (Exception e){
        System.err.println("Error occurred while sending SOAP Request to Server");
        e.printStackTrace();
    }


}

private static SOAPMessage createSOAPRequest() throws Exception {
    MessageFactory messageFactory = MessageFactory.newInstance();
    SOAPMessage soapMessage = messageFactory.createMessage();
    SOAPPart soapPart = soapMessage.getSOAPPart();

    String serverURI = "http://www.wktransportservices.com/schema/mbs/wktsadmin/companyuseraddress/v1_13";

    SOAPEnvelope envelope = soapPart.getEnvelope();
    envelope.addNamespaceDeclaration("exmaple", serverURI);

    SOAPBody soapBody = envelope.getBody();
    SOAPElement soapBodyElem = soapBody.addChildElement("VerifyEmail", "example", "uri");
    SOAPElement soapBodyElem1 = soapBodyElem.addChildElement("email", "example");
    soapBodyElem1.addTextNode("mutantninja@gmail.com");
    SOAPElement soapBodyElem2 = soapBodyElem.addChildElement("LicenseKey", "example");
    soapBodyElem2.addTextNode("123");

    MimeHeaders headers = soapMessage.getMimeHeaders();
    headers.addHeader("SOAPAction", serverURI + "VerifyEmail");

    soapMessage.saveChanges();

    System.out.println("Request SOAP Message = ");
    soapMessage.writeTo(System.out);
    System.out.println();

    return soapMessage;
}

private static void printSOAPResponse(SOAPMessage soapResponse) throws Exception {
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    Source sourceContent = soapResponse.getSOAPPart().getContent();
    System.out.println("\nResponse SOAP Message = ");
    StreamResult streamResult = new StreamResult(System.out);
    transformer.transform(sourceContent, streamResult);
}

}

2 个答案:

答案 0 :(得分:0)

您可以使用okhttpclient。以下是示例代码。

OkHttpClient client = new OkHttpClient();

Request request = new Request.Builder()
    .url("http://www.foo.bar/index.php")
    .put(xml)  // Use PUT on this line.
    .build();

Response response = client.newCall(request).execute();

答案 1 :(得分:0)

新增更新 你能试试这个标题吗?并在添加标题后移动setConfig

put.setHeader("Accept-Charset", "UTF-8");
put.addHeader("Accept", "application/xml");
put.addHeader("Content-type", "application/xml");
put.setConfig(config);

这是另一种选择:

StringEntity params = new StringEntity(data,"UTF-8");
params.setContentType("application/xml");
request.addHeader("Content-type", "application/xml");
request.addHeader("Accept", "*/*");
request.setEntity(params);
put.setConfig(config);

<强>更新

假设您使用的是4.1.3或更高版本的HTTPClient -

构建实体时,我们可以选择为某些实体指定用于POST或PUT操作的内容。有一个ContentType对象应该用于通过使用工厂方法.create()并使用mimetype指定charset来指定它。框架将使用ContentType来正确发出相关标题:

ContentType.create("application/vnd.oma-pcc+xml", CharSet.forName("UTF-8"));

注意 HttpClient 4.1.2

对于4.1.2,当您为post或put操作创建实体时,使用{{1}在实体上设置内容类型而不是执行(HttpPostHttpPut) }}。这在4.1.3及更高版本中已弃用。

您可以使用此代码查找错误,请:

setContentType(String)