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



我的项目上有一个REST Web服务。我尝试使用雷斯特客户端(Google Chrome的扩展名(发送XML PUT请求。我获得了200个成功的成功。现在,我想将相同的XML PUT请求发送到Web服务,但是通过Java代码。

第一解决方案:我使用了apache的httpclient

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允许仅发送获取和发布方法。(我需要发送PUT方法(。当我通过邮政方法发送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);
}

}

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

新更新你可以尝试这个标题吗?并在添加标头后移动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);

update

假设您使用的是4.1.3或更高的httpclient-

构建实体时,我们可以选择指定用于帖子的内容或对某些实体进行操作。有一个ContentType对象,应使用Factory方法.create()并用charset指定mimetype来指定这一点。框架将使用ContentType来正确排放有关的标题:

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

注意 httpclient 4.1.2

在4.1.2的情况下,当您为帖子创建实体或放置操作时,请使用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();
    }
}

相关内容

  • 没有找到相关文章

最新更新