2015-10-07 21 views
1

我用gSOAP開發webservice。其中一種方法返回json輸出。但是,瀏覽器需要傳遞標頭(Access-Control-Allow-Origin)。 gSOAP在發送數據之前是否支持傳遞標題?gSOAP指定訪問控制允許來源

UPD:發現

解決方案。只需添加一些代碼來HTTP_RESPONSE功能:

static int 
http_response(struct soap *soap, int status, size_t count) 
{ 
/* some code goes here*/ 
if ((err = soap->fposthdr(soap, "Access-Control-Allow-Origin", "*"))) 
     return err; 
    if ((err = soap->fposthdr(soap, "Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, CONNECT"))) 
     return err; 
    if ((err = soap->fposthdr(soap, "Access-Control-Allow-Headers", "X-Requested-With, Content-Type"))) 
     return err; 
    if ((err = soap->fposthdr(soap, "Access-Control-Allow-Credentials", "true"))) 
     return err; 
/* some code goes here*/ 
} 

回答

0

我從來沒有找到任何辦法做到這一點在我自己的代碼 - 但我能夠通過修改stdsoap2.cpp這似乎確定這樣做,因爲你需要編譯無論如何你的代碼。我所做的只是HTTP_POST函數結束前添加ClientCertSubjectDN頭:

/******************************************************************************/ 
#ifndef WITH_NOHTTP 
#ifndef PALM_1 
static int 
http_post(struct soap *soap, const char *endpoint, const char *host, int port, const char *path, const char *action, size_t count) 
{ register const char *s; 
    register int err; 
    ... the code of the function (except the return at the end) ... 

    /* add more headers */ 
    if ((err = soap->fposthdr(soap, "ClientCertSubjectDN", "CN=IVR Production"))) 
    return err; 

    return soap->fposthdr(soap, NULL, NULL); 
} 
#endif 
#endif 
+0

我正在使用GET方法。當我嘗試以發佈方式發送標題時,它們會作爲返回文檔的一部分出現。 – vladf

0

其實是有你自己的HTTP標頭添加到不改變gSOAP的代碼服務器的響應莫名其妙麻煩的方式。

  1. 定義一個變量來保存原來的回調掛鉤fposthdr的地址
  2. 定義自己的實現fposthdr的
  3. 上述功能fposthdr的
  4. 店面地址提到的變量
  5. 設置自己的實現fposthdr的
  6. 在你自己實現的fposthdr中使用fposthdr的原始實現來發出HTTP頭文件

代碼例如:

... 
/* Declaration of own implementation of fposthdr */ 
int my_fposthdr(struct soap *soap, const char *key, const char *val); 
/* Definition of variable to store address of original fposthdr */ 
int (*org_fposthdr) (struct soap *soap, const char *key, const char *val) = NULL; 
... 
struct soap *soap 
... 
/* Store address of original function and set own implementation */ 
org_fposthdr = soap->fposthdr; 
soap->fposthdr = my_fposthdr; 
... 
int my_fposthdr(struct soap *soap, const char *key, const char *val) { 
    int res; 
    if (key == NULL) { 
     res = org_fposthdr (soap, "Access-Control-Allow-Origin", "*"); 
     ... 
    } 
    /* Make sure to finally call original fposthdr with key and value being NULL pointers. */ 
    return org_fposthdr (soap, key, val); 
} 
... 

備註: 以上示例性實施方式的my_fposthdr發射畢竟 「默認」 的HTTP標頭由gSOAP的發射的額外HTTP標頭。回調掛鉤由gsoap每頭調用一次,並且在密鑰val的末尾再次爲NULL指針。所以你可以讓你的代碼檢測這些NULL指針併發出你自己的頭文件。最後,您必須撥打密鑰val作爲NULL指針調用原始fposthdr,否則不會發送HTTP負載,即SOAP響應將被髮送。