Home Php C# Sql C C++ Javascript Python Java Go Android Git Linux Asp.net Django .net Node.js Ios Xcode Cocoa Iphone Mysql Tomcat Mongodb Bash Objective-c Scala Visual-studio Apache Elasticsearch Jar Eclipse Jquery Ruby-on-rails Ruby Rubygems Android-studio Spring Lua Sqlite Emacs Ubuntu Perl Docker Swift Amazon-web-services Svn Html Ajax Xml Java-ee Maven Intellij-idea Rvm Macos Unix Css Ipad Postgresql Css3 Json Windows-server Vue.js Typescript Oracle Hibernate Internet-explorer Github Tensorflow Laravel Symfony Redis Html5 Google-app-engine Nginx Firefox Sqlalchemy Lucene Erlang Flask Vim Solr Webview Facebook Zend-framework Virtualenv Nosql Ide Twitter Safari Flutter Bundle Phonegap Centos Sphinx Actionscript Tornado Register | Login | Edit Tags | New Questions | 繁体 | 简体


10 questions online user: 49

0
votes
answers
38 views
+10

我可以在android中的數據消息(FCM)中發送對象嗎?

0

我正在開發一個android應用程序並使用FCM使用PHP-CURL發送數據消息。我無法在任何地方找到我的問題的答案。我可以通過數據消息發送一個對象,而不是隻發送一個簡單的字符串作爲消息嗎?我可以在android中的數據消息(FCM)中發送對象嗎?

沙发
0
2

是的,你可以在使用PHP發送數據時發送一個對象。您將不得不將該對象的hashmap轉換爲前端的JsonObject。它支持FCM和GCM。

0
votes
answers
21 views
+10

提取捲曲API在Android中Java的

0

我嘗試使用以下cURL命令提取從EatStreet API數據:提取捲曲API在Android中Java的

捲曲-X GET -H 'X-訪問令牌:API_EXPLORER_AUTH_KEY' 「https://api.eatstreet.com/publicapi/v1/restaurant/search?latitude=40.4310&longitude=-86.9149&method=both

我寫了到目前爲止的代碼如下:

import org.apache.http.auth.UsernamePasswordCredentials; 
import org.apache.http.client.HttpClient; 
import org.apache.http.client.methods.HttpGet; 
import org.apache.http.impl.auth.BasicScheme; 
import org.apache.http.impl.client.DefaultHttpClient; 

import java.io.BufferedReader; 
import java.lang.StringBuffer; 
import java.net.URI; 
import java.net.URISyntaxException; 


public class Main { 

    public static void main(String[] args) { 
     StringBuffer stringBuffer = new StringBuffer(""); 
     BufferedReader bufferedReader = null; 
     blah(); 
    } 

    private static void blah() { 
     try { 
      HttpClient httpClient = new DefaultHttpClient(); 
      HttpGet httpGet = new HttpGet(); 

      URI uri = new URI("https://api.eatstreet.com/publicapi/v1/restaurant/search?latitude=40.4310&longitude=-86.9149&method=both"); 
      httpGet.setURI(uri); 
      addHeader(httpGet); 
     } 
     catch (URISyntaxException e) { 
      e.printStackTrace(); 
     } 
     catch (Exception e) { 
      e.printStackTrace(); 
     } 
    } 

    private void addHeader(HttpGet httpGet) { 
     httpGet.addHeader(BasicScheme.authenticate(new UsernamePasswordCredentials("X-Access-Token", 
         "__API_EXPLORER_AUTH_KEY__"), null)); 
    } 
} 

此代碼是不是在所有我相信任何輸出是由於WR ong身份驗證。我需要使用Android上面提到的cURL命令來獲取數據。

輸出應該類似於如下(JSON格式):

{ 
    "address": { 
    "apiKey": null, 
    "streetAddress": null, 
    "latitude": 40.431, 
    "longitude": -86.9149, 
    "city": null, 
    "state": null, 
    "zip": null, 
    "aptNumber": null 
    }, 
    "restaurants": [ 
    { 
     "apiKey": "90fd4587554469b1144247b91fbcb2f349e8e58504b5a530", 
     "deliveryMin": 7, 
     "deliveryPrice": 3, 
     "logoUrl": "https://eatstreet-static.s3.amazonaws.com/assets/images/restaurant_logos/egyptian-cafe-and-hooka-bar-29289_1426541949444.png", 
     "name": "Egyptian Cafe and Hooka Bar", 
     "streetAddress": "130 Northwestern Avenue", 
     "city": "West Lafayette", 
     "state": "IN", 
     "zip": "47906", 
     "foodTypes": [ 
     "Subs & Sandwiches", 
     "Middle Eastern Food", 
     "Mediterranean Food", 
     "Hookah Bars", 
     "Healthy Food" 
     ], 
     . 
     . 
     . 
     { 
     "apiKey": "90fd4587554469b1144247b91fbcb2f3720a4edae037dd96", 
     "deliveryMin": 7, 
     "deliveryPrice": 3, 
     "logoUrl": "https://eatstreet-static.s3.amazonaws.com/assets/images/restaurant_logos/vienna-coffee-house-and-bakery-29290_1426542017375.png", 
     "name": "Vienna Coffee House & Bakery", 
     "streetAddress": "208 South Street", 
     "city": "West Lafayette", 
     "state": "IN", 
     "zip": "47906", 
     "foodTypes": [ 
     "Coffee & Tea", 
     "Bakery" 
     ], 
     "phone": "(765) 743-4446", 
     "latitude": 40.4239543, 
     "longitude": -86.9079021, 
     "minFreeDelivery": 0, 
     "taxRate": 0.07, 
     "acceptsCash": false, 
     "acceptsCard": true, 
     "offersPickup": true, 
     "offersDelivery": true, 
     "isTestRestaurant": false, 
     "minWaitTime": 45, 
     "maxWaitTime": 60, 
     "open": true, 
     "url": "https://eatstreet.com/lafayette-in/restaurants/vienna-coffee-house-and-bakery", 
     "hours": { 
     "Sunday": [ 
      "6:00 PM - 12:00 AM" 
     ], 
     "Wednesday": [ 
      "6:00 PM - 12:00 AM" 
     ], 
     "Tuesday": [ 
      "6:00 PM - 12:00 AM" 
     ] 
     }, 
     "timezone": "US/Eastern" 
    } 
    ] 
} 
沙发
0
0

addHeader(httpGet)後,你必須用實際執行的GET操作先前定義的httpClient

HttpResponse response = httpclient.execute(httpGet); 
response.getEntity().getContent(); // do something with the response 
// an example of continuing what you were trying to do 
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(
     response.getEntity().getContent())); 

而且,您的addHeader(httpGet)需要更改爲此,以傳遞API密鑰作爲標題,而不是UsernamePasswordCredentials

private static void addHeader(HttpGet httpGet) { 
     httpGet.addHeader("X-Access-Token", "__API_EXPLORER_AUTH_KEY__"); 
} 
0
votes
answers
17 views
+10

pushcrew - 用PHP發送通知捲曲

0

這是代碼:pushcrew - 用PHP發送通知捲曲

$title = 'Du hast neue Nachricht'; 
    $message = 'Besuch meine Website'; 
    $url = 'https://www.bla.com'; 
    $subscriberId = 'xxx51a002dec08a1690fcbe6e'; 

    $apiToken = 'xxxe0b282d9c886456de0e294ad'; 

    $curlUrl = 'https://pushcrew.com/api/v1/send/individual/'; 

    //set POST variables 
    $fields = array(
     'title' => $title, 
     'message' => $message, 
     'url' => $url, 
     'subscriber_id' => $subscriberId 
    ); 

    $httpHeadersArray = Array(); 
    $httpHeadersArray[] = 'Authorization: key='.$apiToken; 

    //open connection 
    $ch = curl_init(); 

    //set the url, number of POST vars, POST data 
    curl_setopt($ch, CURLOPT_URL, $curlUrl); 
    curl_setopt($ch, CURLOPT_POST, true); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($fields)); 
    curl_setopt($ch, CURLOPT_HTTPSHEADER, $httpHeadersArray); 

    //execute post 
    $result = curl_exec($ch); 

    $resultArray = json_decode($result, true); 

    if($resultArray['status'] == 'success') { 
     echo $resultArray['request_id']; //ID of Notification Request 
    } 
    else if($resultArray['status'] == 'failure') 
    { 
     echo 'fail'; 
    } 
    else 
    { 
     echo 'dono'; 
    } 

    echo '<pre>'; 
    var_dump($result); 
    echo '</pre>'; 

我也得到:

dono 
string(36) "{"message":"You are not authorized"}" 
控制檯並沒有其他錯誤

並沒有什麼。 apitoken是100%正確的。這裏有什麼麻煩?我是否必須等到推釘機決定允許我的網站或其他東西?

忽略這一點:我必須添加一些文字來問這個問題..

沙发
0
0

有錯字這裏:

curl_setopt($ch, CURLOPT_HTTPSHEADER, $httpHeadersArray); 

正確的是

CURLOPT_HTTPHEADER

(不S

+0

終於它的作品謝謝! – user2966167

0
votes
answers
31 views
+10

如何將curl寫入php?

0

我有這下面的PHP腳本。我想用curl添加調用函數。 如何在我的下面的腳本上寫入捲曲?如何將curl寫入php?

我是編程新手。我仍然很好地學習它。請檢查我的代碼並嘗試幫助我添加捲曲。

我的腳本沒有錯誤。只是我想添加php函數替換爲curl函數。

我希望如此,你明白。對不起,我的英語不好。感謝

我的代碼是在這裏:

$url = 'https://web.facebook.com/'.$pageid.'/videos/'.$id.'/'; 

$context = [ 
    'http' => [ 
     'method' => 'GET', 
     'header' => "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.47 Safari/537.36", 
    ], 
]; 
$context = stream_context_create($context); 
$data = file_get_contents($url, false, $context); 

function cleanStr($str) 
{ 
    return html_entity_decode(strip_tags($str), ENT_QUOTES, 'UTF-8'); 
} 

function hd_finallink($curl_content) 
{ 

    $regex = '/hd_src_no_ratelimit:"([^"]+)"/'; 
    if (preg_match($regex, $curl_content, $match)) { 
     return $match[1]; 

    } else {return;} 
} 

function sd_finallink($curl_content) 
{ 

    $regex = '/sd_src_no_ratelimit:"([^"]+)"/'; 
    if (preg_match($regex, $curl_content, $match1)) { 
     return $match1[1]; 

    } else {return;} 
} 


$hdlink = hd_finallink($data); 
$sdlink = sd_finallink($data); 

if ($sdlink || $hdlink) { 

echo '<a href="'.$hdlink.'" download="hd.mp4" class="link">HD Download </a>'; 
echo '<a href="'.$sdlink.'" download="sd.mp4" class="link">SD Download </a>'; 

} else { 

echo 'Download not showing - Please Reload This Page'; 

} 
沙发
0
1

之前,我們可以用捲曲的要求做任何事情,我們需要首先實例捲曲的一個實例 - 我們可以通過調用函數做到這一點curl_init();

對於GET請求示例代碼:用於POST

// Get cURL resource 
$curl = curl_init(); 
// Set some options - we are passing in a useragent too here 
curl_setopt_array($curl, array(
    CURLOPT_RETURNTRANSFER => 1, 
    CURLOPT_URL => 'http://testcURL.com/?item1=value&item2=value2', 
    CURLOPT_USERAGENT => 'Codular Sample cURL Request' 
)); 
// Send the request & save response to $resp 
$resp = curl_exec($curl); 
// Close request to clear up some resources 
curl_close($curl); 

示例代碼熱曲斯:

// Get cURL resource 
$curl = curl_init(); 
// Set some options - we are passing in a useragent too here 
curl_setopt_array($curl, array(
    CURLOPT_RETURNTRANSFER => 1, 
    CURLOPT_URL => 'http://testcURL.com', 
    CURLOPT_USERAGENT => 'Codular Sample cURL Request', 
    CURLOPT_POST => 1, 
    CURLOPT_POSTFIELDS => array(
     item1 => 'value', 
     item2 => 'value2' 
    ) 
)); 
// Send the request & save response to $resp 
$resp = curl_exec($curl); 
// Close request to clear up some resources 
curl_close($curl); 

See this link

+0

怎麼我把它替換到我的PHP。請用完整的代碼更新您的代碼。謝謝 –

+0

'$ resp = shell_exec('curl -s -d item1 = value -d item2 = value2 http://testcURL.com');'' – hanshenrik

0
votes
answers
18 views
+10

登錄從HTTPS提交表單使用curl

0

我需要使用POST(asp.net),我讀到有關從這裏這個話題,外部網站提交登錄表單和幾個例子我不能使它工作。登錄從HTTPS提交表單使用curl

我知道我發出正確的參數,因爲使用郵遞員進行測試,當我回到家HTML的響應,所以它一定是壞了,我的代碼做的,這就是我想要的此刻:

// Create temp file to store cookies 
$ckfile = tempnam ("/tmp", "CURLCOOKIE"); 

// URL to login page 
$url = "https://site/Login.aspx"; 

// Get Login page and its cookies and save cookies in the temp file 
$ch = curl_init(); 
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true); // Accepts all CAs 
curl_setopt($ch, CURLOPT_URL, $url); 
curl_setopt($ch, CURLOPT_COOKIEJAR, $ckfile); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
$output = curl_exec($ch); 

$fields = array(
'ctl00$ContentPlaceHolder1$txtUser' => 'user', 
'ctl00$ContentPlaceHolder1$txtPassword' => '******', 
'__VIEWSTATEGENERATOR'=> '716EFC3E', 
'__EVENTVALIDATION'=> 'dfsgsdf5463456', 
'__LASTFOCUS'=> '', 
'__EVENTTARGET'=> '', 
'__EVENTARGUMENT'=> '', 
'__VIEWSTATE'=> 'wEPDwUKLTM1Mjk0NzM0Mw9kFgJmD2QWAgIDD2QWAgID', 
'ctl00$ContentPlaceHolder1$btnLogin'=> 'In', 
); 

$fields_string = ''; 
foreach($fields as $key=>$value) { 
$fields_string .= $key . '=' . $value . '&'; 
} 
rtrim($fields_string, '&'); 

// Post login form and follow redirects 
$ch = curl_init(); 
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true); // I also try it with false 
curl_setopt($ch, CURLOPT_URL, $url); 
curl_setopt($ch, CURLOPT_POST, count($fields)); 
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string); 
curl_setopt($ch, CURLOPT_COOKIEFILE, $ckfile); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); 
$output = curl_exec($ch); 

echo $output; 
curl_close($ch); 

這是一個通用的服務器運行時錯誤。

我在做什麼錯了?

沙发
0
0

許多/大多數登錄頁面使用您需要登錄表單刮一次性使用的安全令牌值。

工作流程是這樣的:

  1. 抓取登錄頁面
  2. 刮(解析,提取物)從尋呼響應一次性令牌
  3. 使用令牌

提交表單你的代碼看起來像是使用陳舊的硬編碼的令牌。

+0

如果這是真的,如何使用時,郵遞員來與相同參數的實際工作?這就是爲什麼我很迷惑 – elunap

+0

您的代碼可能沒有發送一模一樣的餅乾和/或參數,但我們需要看到真正的網站才能夠告訴你更多。你可以使用一個數據包嗅探器工具(在PC上是一個很好的Fiddler2)捕獲郵遞員流量和你的php流量? –

699
votes
answers
19 views
+10

HTTP POST and GET using cURL in Linux [duplicate]

This question already has an answer here:

I have a server application written in ASP.NET on Windows that provides a web service.

How can I call the web service in Linux with cURL?

沙发
+6490

*nix provides a nice little command which makes our lives a lot easier.

GET:

with JSON:

curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource

with XML:

curl -H "Accept: application/xml" -H "Content-Type: application/xml" -X GET http://hostname/resource

POST:

For posting data:

curl --data "param1=value1&param2=value2" http://hostname/resource

For file upload:

curl --form "fileupload=@filename.txt" http://hostname/resource

RESTful HTTP Post:

curl -X POST -d @filename http://hostname/resource

For logging into a site (auth):

curl -d "username=admin&password=admin&submit=Login" --dump-header headers http://localhost/Login
curl -L -b headers http://localhost/

Pretty-printing the curl results:

For JSON:

If you use npm and nodejs, you can install json package by running this command:

npm install -g json

Usage:

curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource | json

If you use pip and python, you can install pjson package by running this command:

pip install pjson

Usage:

curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource | pjson

If you use Python 2.6+, json tool is bundled within.

Usage:

curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource | python -m json.tool

If you use gem and ruby, you can install colorful_json package by running this command:

gem install colorful_json

Usage:

curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource | cjson

If you use apt-get (aptitude package manager of your Linux distro), you can install yajl-tools package by running this command:

sudo apt-get install yajl-tools

Usage:

curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource |  json_reformat

For XML:

If you use *nix with Debian/Gnome envrionment, install libxml2-utils:

sudo apt-get install libxml2-utils

Usage:

curl -H "Accept: application/xml" -H "Content-Type: application/xml" -X GET http://hostname/resource | xmllint --format -

or install tidy:

sudo apt-get install tidy

Usage:

curl -H "Accept: application/xml" -H "Content-Type: application/xml" -X GET http://hostname/resource | tidy -xml -i -

Saving the curl response to a file

curl http://hostname/resource >> /path/to/your/file

or

curl http://hostname/resource -o /path/to/your/file

For detailed description of the curl command, hit:

man curl

For details about options/switches of the curl command, hit:

curl -h

在獲取示例中,您可以引用整個URL來避免params上的錯誤,例如捲曲“http://www.virustotal.com/vtapi/v2/ip-address/report?ip=8.8.8.8&apikey=1233456890” - 里卡多17年6月26日22:44

板凳
+500

I think Amith Koujalgi is correct but also, in cases where the webservice responses are in JSON then it might be more useful to see the results in a clean JSON format instead of a very long string. Just add | grep }| python -mjson.tool to the end of curl commands here is two examples:

GET approach with JSON result

curl -i -H "Accept: application/json" http://someHostName/someEndpoint | grep }| python -mjson.tool 

POST approach with JSON result

curl -X POST  -H "Accept: Application/json" -H "Content-Type: application/json" http://someHostName/someEndpoint -d '{"id":"IDVALUE","name":"Mike"}' | grep }| python -mjson.tool

enter image description here

什麼是grep應該在這裡做什麼?我使用以下相同的結果:curl -s -H“Accept:application / json”-H“Content-Type:application / json”-H“http:// $ {API_BASE_URL} $ {1}”| python -mjson.tool - AVProgrammer 2016年7月21日14:14

你能不能看看我的問題stackoverflow.com/questions/47526927 / ... - srinivas gowda 17年11月29日在9:20

0
votes
answers
24 views
+10

Instagram的API捲曲代碼命令到PHP

0

我找不到在PHP捲曲相當於此命令Instagram的API捲曲代碼命令到PHP

curl -F 'client_id=CLIENT_ID'  
 
    -F 'client_secret=CLIENT_SECRET'  
 
    -F 'grant_type=authorization_code'  
 
    -F 'redirect_uri=AUTHORIZATION_REDIRECT_URI'  
 
    -F 'code=CODE'  
 
    https://api.instagram.com/oauth/access_token

我知道它應該開始像

$ch = curl_init('https://api.instagram.com/oauth/access_token'); 
 
curl_setopt($ch, something, ...); 
 
... 
 
...

沙发
0
0

其中的當量與

curl -F 'client_id=CLIENT_ID'  
    -F 'client_secret=CLIENT_SECRET'  
    -F 'grant_type=authorization_code'  
    -F 'redirect_uri=AUTHORIZATION_REDIRECT_URI'  
    -F 'code=CODE'  
    https://api.instagram.com/oauth/access_token 

$url = 'https://api.instagram.com/oauth/access_token'; 
$fields = array(
    'client_id' => 'CLIENT_ID', 
    'client_secret' => 'CLIENT_SECRET', 
    'grant_type' => 'authorization_code', 
    'redirect_uri' => 'AUTHORIZATION_REDIRECT_URI', 
    'code' => 'CODE' 
); 

$ch = curl_init(); 

curl_setopt($ch,CURLOPT_URL, $url); 
curl_setopt($ch,CURLOPT_POST, count($fields)); 
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string); 

$result = curl_exec($ch); 

curl_close($ch); 

希望我幫助! -CM

+0

但什麼是$ fields_string?你的意思是$字段? –

0
votes
answers
26 views
+10

創建交易機器人的例外

0

我正在嘗試創建WordPress插件,該插件在PHP中爲我的網站交易cryptocoins,並且我試圖使用Bittrex API實現此目的。創建交易機器人的例外

我的問題是,當我嘗試從API調用方法,引發異常。 有人可以幫我找到我的代碼中的問題?

這裏是主類中的代碼,我從Client類創建一個對象。

require 'bittrex-master/src/edsonmedina/bittrex/Client.php'; 
use edsonmedinaittrexClient; 

$keya = "xxx"; 
$secreta = "xxx"; 

$b = new Client ($keya, $secreta); 

try{ 
    $list = $b->getMarkets(); 
    echo "$list"; 

}catch (Exception $e) { 
    echo 'Caught exception: ', $e->getMessage(), "
"; 
} 

echo "

"; 

下面是代碼從客戶端類

namespace edsonmedinaittrex; 

class Client 
{ 
private $baseUrl; 
private $apiVersion = 'v1.1'; 
private $apiKey; 
private $apiSecret; 

public function __construct ($apiKey, $apiSecret) 
{ 
    $this->apiKey = $apiKey; 
    $this->apiSecret = $apiSecret; 
    $this->baseUrl = 'https://bittrex.com/api/'.$this->apiVersion.'/'; 
} 

/** 
* Invoke API 
* @param string $method API method to call 
* @param array $params parameters 
* @param bool $apiKey use apikey or not 
* @return object 
*/ 
private function call ($method, $params = array(), $apiKey = false) 
{ 
    $uri = $this->baseUrl.$method; 

    if ($apiKey == true) { 
     $params['apikey'] = $this->apiKey; 
     $params['nonce'] = time(); 
    } 

    if (!empty($params)) { 
     $uri .= '?'.http_build_query($params); 
    } 

    $sign = hash_hmac ('sha512', $uri, $this->apiSecret); 

    $ch = curl_init ($uri); 
    curl_setopt ($ch, CURLOPT_HTTPHEADER, array('apisign: '.$sign)); 
    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true); 
    $result = curl_exec($ch); 

    $answer = json_decode($result); 

    if ($answer->success == false) { 
     throw new Exception ($answer->message); 
    } 

    return $answer->result; 
} 

/** 
* Get the open and available trading markets at Bittrex along with other meta data. 
* @return array 
*/ 
public function getMarkets() 
{ 
    return $this->call ('public/getmarkets'); 
} 
+1

什麼是例外? – valtron

+0

沒有特定的例外情況。唯一的輸出是「捕獲的異常:」,這是在引發異常時的輸出 –

+0

調試!去穴居人,並添加打印語句,以查找例外情況。 – zaph

沙发
0
1

根據您的意見和異常APIKEY_NOT_PROVIDEDcall方法的一部分,默認情況下你的APIKEY是假的。

return $this->call ('public/getmarkets', null, true); 
+0

非常感謝您解決我的問題的幫助 –

0
votes
answers
29 views
+10

將cURL代碼轉換爲c#izooto api

1

我正在嘗試訪問api以進行推送通知。將cURL代碼轉換爲c#izooto api

這是捲曲代碼:

curl -X POST  
    -H "Authentication-Token: {API_TOKEN}"  
    -H "Content-Type: application/json"  
    -d '{ 
    "title" : "{NOTIFICATION_TITLE}", 
    "message" : "{NOTIFICATION_MESSAGE}", 
    "icon_url" : "{ICON_URL}", 
    "banner_url" : "{BANNER_URL}", 
    "landing_url" : "{LANDING_URL}", 
    "actions" : [ 
     { 
     "text" : "{BUTTON1_TEXT}", 
     "url" : "{BUTTON1_URL}" 
     }, 
     { 
     "text" : "{BUTTON2_TEXT}", 
     "url" : "{BUTTON2_URL}" 
     }], 
    "utm_source" : "{UTM_SOURCE}", 
    "utm_medium" : "{UTM_MEDIUM}", 
    "utm_campaign" : "{UTM_CAMPAIGN}", 
    "ttl" : {TTL_SECONDS}, 
    "target" : { 
      "type" : "all" 
    } 
    }' "https://apis.izooto.com/v1/notifications" 

我試圖通過C#來訪問API。

C#代碼:

public string get() 
    { 
     try 
     { 
      WebRequest tRequest; 
      tRequest = WebRequest.Create("https://apis.izooto.com/v1/notifications"); 
      tRequest.Method = "post"; 
      tRequest.ContentType = "multipart/form-data"; 
      tRequest.Headers.Add("Authentication-Token", "xxxxxxxxx-yyyyyyyyy"); 

      string imgurl = "https://cdnimg.izooto.com/9338/9883/93381513921358.png"; 
      string landing_url = "http://www.maalaimalar.com/News/TopNews/2017/12/27110835/1136906/MK-Stalin-Slams-his-Brother-MK-Stalin-for-RK-Nagar.vpf"; 
      string postData = "title=test&message=testmsg&icon_url=" + imgurl + "&landing_url=" + landing_url + ""; 

      Console.WriteLine(postData); 

      Byte[] byteArray = Encoding.UTF8.GetBytes(postData); 
      tRequest.ContentLength = byteArray.Length; 
      Stream dataStream = tRequest.GetRequestStream(); 

      dataStream.Write(byteArray, 0, byteArray.Length); 
      dataStream.Close(); 
      WebResponse tResponse = tRequest.GetResponse(); 

      dataStream = tResponse.GetResponseStream(); 
      StreamReader tReader = new StreamReader(dataStream); 
      String sResponseFromServer = tReader.ReadToEnd(); 

      //lblStat.Text = sResponseFromServer; 
      tReader.Close(); 
      dataStream.Close(); 
      tResponse.Close(); 
      return sResponseFromServer; 
     } 
     catch (Exception e) 
     { 
      return e.Message; 
     } 
    } 

到達時,我收到以下錯誤WebResponse tResponse = tRequest.GetResponse();

錯誤:System.Net.WebException: The remote server returned an error: (400) Bad Request.

響應:{"success":false,"message":"Authentication token missing"}

我提到以下文檔卷曲碼 https://docs.izooto.com/docs/push-to-all 任何人都可以爲此提供解決方案。提前致謝。

+0

看起來對我來說,它希望JSON,但你要發送表單數據。 – Crowcoder

+0

我也嘗試過使用「application/json」 –

+0

你不能只改變內容類型頭,你還必須給POST Body有效的JSON。 – Crowcoder

沙发
0
2

通行證目標在下面postData.Like,

string postData= "{
 "title" : ""+ title + "",
 "message" : ""+ message + "",
 "icon_url" : ""+ icon_url + "",
 "banner_url" : "" + bannerUrl + "",
 "landing_url" : "" + landing_url + "",
 "target" : {
   "type" : "all"
 }
 }"; 
0
votes
answers
29 views
+10

Laravel:多捲圖像上傳問題(在REST API中)捲曲和郵差

0

上傳多個圖像在postman/curl的larvel rest api中無法正常工作。 它只插入一個圖像。Laravel:多捲圖像上傳問題(在REST API中)捲曲和郵差

在視圖中使用larvel上傳表單根本沒有問題,它工作正常。

<input type="file" name="image[]" multiple /> 

我在嘗試的是上傳多個圖像郵遞員和curl在Laravel休息api。

這是控制文件

public function uploadimages(Request $request){ 
      $files = $request->allFiles('image');  
      $count = 0;  
      foreach ($files as $file) { 
       $file->store('public/uploads'); 
       $count++; 
       //this technic also not work 
       /* $name= $file->getClientOriginalName(); 
        $file->move('public/uploads', $name); 
        $images[]=$name;*/ 
      } 
      //$count return only 1(it only upload one file) 
      return response()->json($count, 201); 
    } 

這是我的curl命令

curl -X POST http://localhost:8000/api/uploadimages -H "Content-Type: multipart/form-data" -F "[email protected]/C:xampphtdocs2.jpg" -F "[email protected]/C:xampphtdocs1.jpg" 

這個命令插入只有一個文件。

我也把這個和嘗試「image [] = @/C: xampp htdocs 1.jpg」並得到錯誤。

curl -X POST http://localhost:8000/api/uploadimages -H "Content-Type: multipart/form-data" -F "image[][email protected]/C:xampphtdocs2.jpg" -F "image[][email protected]/C:xampphtdocs1.jpg" 
    % Total % Received % Xferd Average Speed Time Time  Time Current 
           Dload Upload Total Spent Left Speed 
    0  0 0  0 0  0  0  0 --:--:-- --:--:-- --:--:--  0 
curl: (26) couldn't open file "/C:xampphtdocs2.jpg" 

在郵遞員應用程序中也只上傳一個文件。 我仔細檢查郵遞員設置從其他問題上傳文件。我認爲設置是可以的。

我無法找到上傳Larvel Rest api中的多個圖像。

有什麼問題,請有人建議我,並解釋我的問題。

沙发
0
1

我認爲你的問題是你試圖用相同的密鑰發送2個文件。在這種情況下爲image。嘗試更改第二個文件密鑰到其他東西像image2所以它會像

curl -X POST http://localhost:8000/api/uploadimages -H "Content-Type: multipart/form-data" -F "[email protected]/C:xampphtdocs2.jpg" -F "[email protected]/C:xampphtdocs1.jpg" 
+0

謝謝@avpav,它的工作。我被困了很多天。你幫我。非常感謝。 –

+0

有一點,你有什麼想法建議,爲什麼它不適用於postman應用程序? –

+0

我不知道。你能提供一個截圖嗎? – avpav