Web服务客户端应用程序

时间:2014-11-24 12:49:57

标签: java xml web-services

有一个.Net Web服务,我必须从本地应用程序发送XML数据。我的本地应用程序在Java& SQL。

Web服务正在接受xml类型。你能帮帮我怎么办?这个案子有一个例子吗?

1 个答案:

答案 0 :(得分:0)

我将从您的Java应用程序中提供2个示例,您将文件发布到服务中。

Apache HttpClient:

String url = "https://yoururl.com"; 

HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);

// add header
post.setHeader("User-Agent", USER_AGENT);

List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
urlParameters.add(new BasicNameValuePair("xml", xmlString));

post.setEntity(new UrlEncodedFormEntity(urlParameters));

HttpResponse response = client.execute(post);
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + post.getEntity());
System.out.println("Response Code : " + 
                            response.getStatusLine().getStatusCode());

BufferedReader rd = new BufferedReader(
                new InputStreamReader(response.getEntity().getContent()));

StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
    result.append(line);
}

System.out.println(result.toString());

以下是如何使用 java.net.URLConnection:

进行操作的示例
String url = "http://example.com";
String charset = "UTF-8";
String param1 = URLEncoder.encode("param1", charset);
String param2 = URLEncoder.encode("param2", charset);
String query = String.format("param1=%s&param2=%s", param1, param2);

URLConnection urlConnection = new URL(url).openConnection();
urlConnection.setUseCaches(false);
urlConnection.setDoOutput(true); // Triggers POST.
urlConnection.setRequestProperty("accept-charset", charset);
urlConnection.setRequestProperty("content-type", "application/x-www-form-urlencoded");

OutputStreamWriter writer = null;
try {
    writer = new OutputStreamWriter(urlConnection.getOutputStream(), charset);
    writer.write(query); // Write POST query string (if any needed).
} finally {
    if (writer != null) try { writer.close(); } catch (IOException logOrIgnore) {}
}

InputStream result = urlConnection.getInputStream();
// Now do your thing with the result.

谢谢

Shiva Kumar SS