从XML文件向Web服务发出多个HTTP post请求

时间:2015-06-09 10:54:22

标签: c# multithreading soap xmlhttprequest

我想在C#中向Web服务发送多个HTTP post请求。例如,如果n = 3,则应该发出来自3 xml文件的http post请求。那么我该如何实现呢?我只需要想法。我认为可以创建n个线程,每个线程将执行一个http post请求。如果可能的话,代码中也会有点帮助。谢谢。

2 个答案:

答案 0 :(得分:2)

此代码有效。 解释:

  • 首先,用户提供.xml文件的源和目标路径。
  • Directory.getFiles()帮助我们获取字符串数组中的.xml文件。 (我们必须传递.xml作为参数)。

  • 现在基本上发生的事情是我们在源代码处获得的每个文件,都会创建一个帖子。

  • 但是如果用户想要发送" n"一次请求,然后一次创建n个线程。
  • 除非先前的线程执行完毕,否则不会创建下一组线程。
  • 这是由thread.Join()确保的。
  • 在向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();
        }
    }
    

    } }

答案 1 :(得分:0)

使用java.util.concurrent.ExecutorService正如Java规范所说:

  

Executor,提供管理终止和方法的方法   这可以产生一个跟踪一个或多个进度的Future   异步任务。

因此,使用ExecutorService的实现,您可以在给定数量的线程中异步或同步地运行所有任务。为此,您需要创建一个Callable对象列表,并将其传递给ExecutorService对象的invokeAll方法。 invokeAll方法将返回Future对象列表的列表(每个Future对象将代表每个任务,并且顺序与传递给invokeAll方法的Callable列表中的顺序相同),您可以循环总计任务的所有结果并打印它。 / p>

您应该阅读Executors类的所有可用方法,这些方法返回ExecutorService的不同实例,因此请选择适合您的方法。

通过这种方式,您将能够在M个给定线程中运行N个任务(这是您的HTTP请求),一旦完成所有线程,您将获得Future对象列表,它将为您提供完成信息/状态每项任务。

请确保线程中的异常处理,因为它们不会传播,您需要显式打印堆栈跟踪。

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

检查以下psuedo示例: