【问题标题】:How to send XML PUT request via Java Code如何通过 Java 代码发送 XML PUT 请求
【发布时间】:2017-04-18 05:23:21
【问题描述】:

我的项目中有一个 REST Web 服务。 我尝试使用 Restlet Client(Google Chrome 的扩展)发送 XML PUT 请求。 我收到了 200 OK 成功。 现在我想通过 JAVA CODE 向 Web 服务发送相同的 XML PUT 请求。

第一个解决方案: 我使用了 Apache 的 HttpClient,但它返回 org.apache.http.NoHttpResponseException: failed to respond

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

}

回复

org.apache.http.NoHttpResponseException: failed to respond

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

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

}

【问题讨论】:

  • 这是客户端你有服务器端实现吗?看起来服务器没有响应你的请求~
  • 我尝试通过 Restlet(Google Chrome 扩展程序)向服务器发送 XML PUT 请求,它可以工作!我收到 200 状态码成功!服务器没问题!
  • 可以逐行调试吗?我不知道问题出在哪里。我看起来连接断开了。您使用的是哪个版本的 HttpClient?
  • 此处抛出异常:“ HttpResponse response = client.execute(put);”线程“主”org.apache.http.NoHttpResponseException 中的异常:响应失败
  • 好的,现在我们知道在执行中,所以我们有 2 个主要选项。 put 对象配置不当或 HTTPClient 未处理响应或未发送请求。

标签: java xml web-services http soap


【解决方案1】:

你可以使用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();

【讨论】:

  • 不行,XML不能是字符串,需要为它创建一个RequestBody对象。
【解决方案2】:

新的更新 你可以试试这个标题吗?并在添加标题后移动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() 并用charset 指定mimetype 来指定它。框架将使用ContentType 来正确发出有问题的标头:

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

注意 HttpClient 4.1.2

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

你能用这段代码找出错误吗,拜托:

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();
    try {
        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());

        responseCode = response.getStatusLine().getStatusCode();
        if (response.getStatusLine().getStatusCode() == 200 || response.getStatusLine().getStatusCode() == 204) 
            //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);
            }
        } else {
            System.out.println(response.getStatusLine().getStatusCode());

            throw new RuntimeException("Failed : HTTP error code : "
                    + response.getStatusLine().getStatusCode());
        }
    }catch (Exception ex) {
        System.out.println("ex Code sendPut: " + ex);
    } finally {
        httpClient.getConnectionManager().shutdown();
    }

}

【讨论】:

  • ex Code sendPut: org.apache.http.NoHttpResponseException: failed to respond
  • 我认为是HTTPClient的版本。
  • 如你所说,我将 HTTPClient 的版本更改为 4.1.2。并且找不到 RequestConfig 类和 HttpClientBuilder。设置代理需要请求配置(我需要使用代理)。有什么想法吗?
  • 不,你没有告诉我你的版本,所以我给了两个选择。但是,我建议您使用最新版本。如果您更新版本,请告诉我。
  • 我认为服务器不接受标头,因此您没有收到任何响应。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-03
  • 1970-01-01
相关资源
最近更新 更多