简体   繁体   English

从 XML 文件到 Web 服务的多个 HTTP post 请求

[英]Multiple HTTP post requests to a web service from XML files

I want to send multiple HTTP post requests to a Web Service in C# .For example , if n=3 then http post requests from 3 xml files should be made.我想向 C# 中的 Web 服务发送多个 HTTP post 请求。例如,如果 n=3,则应该发出来自 3 个 xml 文件的 http post 请求。 So how can i implement this ?那么我该如何实现呢? I just need ideas.我只需要想法。 I think n threads can be created and each thread will execute one http post request.我认为可以创建 n 个线程,每个线程将执行一个 http post 请求。 If possible a bit assisstance in code as well.如果可能的话,在代码中也有一些帮助。 Thank you.谢谢你。

This code works .此代码有效。 Explaination :说明:

  • Firstly the user gives the source and destination paths for the .xml files.首先,用户给出 .xml 文件的源路径和目标路径。
  • Directory.getFiles() helps us to get the .xml files in the string array . Directory.getFiles() 帮助我们获取字符串数组中的 .xml 文件。 (we have to pass .xml as a parameter) . (我们必须将 .xml 作为参数传递)。

  • SO now what basically happens is for each file we get at the source pat , a thread is created .所以现在基本上发生的是对于我们在源 pat 处获得的每个文件,都会创建一个线程。

  • But say if the user wants to send "n" requests at a time , then n threads are created at a time.但是如果用户想一次发送“n”个请求,那么一次创建 n 个线程。
  • And the next set of threads are not created unless the previous threads are finished executing.除非前一个线程完成执行,否则不会创建下一组线程。
  • This is ensured by thread.Join().这是由 thread.Join() 确保的。
  • And after a request is made to the web service , we get the response by getResponse() and the response is written in .xml files which are stored at the destination paths.在向 Web 服务发出请求后,我们通过 getResponse() 获得响应,并将响应写入存储在目标路径中的 .xml 文件中。

     using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Threading; using System.Xml; using System.Net; namespace ConsoleApplication4 { class Program { int flag = 1; string destination; string source; static void Main(string[] args) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("**************************** Send HTTP Post Requests **************************"); int n = 0; Program p = new Program(); Console.WriteLine("Enter the number of requests you want to send at a time"); string s = Console.ReadLine(); int.TryParse(s, out n); Console.WriteLine("Enter Source"); p.source = Console.ReadLine(); Console.WriteLine("Enter Destination"); p.destination = Console.ReadLine(); string[] files = null; files = Directory.GetFiles(p.source, "*.xml", SearchOption.TopDirectoryOnly); Thread[] thread = new Thread[files.Length]; int len = files.Length; for (int i = 0; i<len; i+=n) { int x = i; //Thread.Sleep(5000); for (int j = 0; j < n && x < len; j++) { var localx = x; thread[x] = new Thread(() => function(files[localx], p)); thread[x].Start(); Thread.Sleep(50); //thread[x].Join(); x++; } int y = x - n; for (; y < x; y++) { int t = y; thread[t].Join(); } } // thread[0] = new Thread(() => function(files[0])); //thread[0].Start(); Console.ReadKey(); } public static void function(string temp,Program p) { XmlDocument doc = new XmlDocument(); doc.Load(temp); string final_d=p.destination + "response " + p.flag + ".xml"; p.flag++; HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://10.76.22.135/wpaADws/ADService.asmx"); request.ContentType = "text/xml;charset=\\"utf-8\\""; request.Accept = "text/xml"; request.Method = "POST"; Stream stream = request.GetRequestStream(); doc.Save(stream); stream.Close(); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); using (StreamReader rd = new StreamReader(response.GetResponseStream())) { string soapResult = rd.ReadToEnd(); doc.LoadXml(soapResult); File.WriteAllText(final_d, doc.DocumentElement.InnerText); //XmlTextWriter xml=new XmlTextWriter( Console.WriteLine(soapResult); //Console.ReadKey(); } }

    } } } }

Use java.util.concurrent.ExecutorService As Java specs says:使用 java.util.concurrent.ExecutorService 正如 Java 规范所说:

An Executor that provides methods to manage termination and methods that can produce a Future for tracking progress of one or more asynchronous tasks.一个 Executor 提供管理终止的方法和可以生成 Future 以跟踪一个或多个异步任务的进度的方法。

So, using an implementation of ExecutorService you can run all your tasks asynchronously or synchronously in given number of threads.因此,使用 ExecutorService 的实现,您可以在给定数量的线程中异步或同步运行所有任务。 For that you need to create a list of Callable objects and pass it to invokeAll method of object of ExecutorService.为此,您需要创建一个 Callable 对象列表并将其传递给 ExecutorService 对象的 invokeAll 方法。 invokeAll method will return list of list of Future objects (Each Future object will represent each task, and order is same as you put in Callable list passed to invokeAll method) which you can loop total all the result of the task and print it. invokeAll 方法将返回 Future 对象列表的列表(每个 Future 对象将代表每个任务,顺序与您放入传递给 invokeAll 方法的 Callable 列表中的顺序相同),您可以循环计算任务的所有结果并打印它。

You should read all available methods of Executors class which return different instances of ExecutorService, so choose the one which suits you.您应该阅读 Executors 类的所有可用方法,这些方法返回 ExecutorService 的不同实例,因此选择适合您的方法。

In this way, you will be able to run your N tasks (which are your HTTP requests) in M given threads, and once all the threads are finished you will get list of Future objects which will give you completion information/status of each task.通过这种方式,您将能够在 M 个给定线程中运行您的 N 个任务(即您的 HTTP 请求),一旦所有线程完成,您将获得 Future 对象列表,这些对象将为您提供每个任务的完成信息/状态.

Please be sure about exception handling in threads, because they don't get propagated, you need to explicitly print the stacktrace.请确保线程中的异常处理,因为它们不会传播,您需要显式打印堆栈跟踪。

try {
    List<Callable<Object>> callableList = new ArrayList<Callable<Object>>();
    callableList.add(null); /*Add instance of Callable, which would have your HTTP request code in its overridden call() method*/
    callableList.add(null); /*Add instance of Callable*/
    callableList.add(null); /*Add instance of Callable*/

    //Specify how many threads you want or need to operate. Read other methods of Executors which return different instances of ExecutorService
    final ExecutorService service = Executors.newFixedThreadPool(3);

    //This will invoke all your N tasks in specified M threads ...
    List<Future<String[]>> futureObjects = service.invokeAll(callableList);  //futureObjects will contain result of each thread execution
} catch (InterruptedException e) {
    e.printStackTrace();
}

Check below psuedo example:检查以下伪示例:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM