Error code 7 specify xml or json param error

Не получается получить json от yandex PHP Решение и ответ на вопрос 1718131

Geri4

0 / 0 / 2

Регистрация: 15.01.2015

Сообщений: 46

1

22.04.2016, 14:00. Показов 3337. Ответов 5

Метки нет (Все метки)


Помогите кто чем сможет плиз…
Есть ресурс такой api.lbs.yandex.net/geolocation.
Мне нужно отправить post запрос в формате json и получить в ответ. Я не могу не чего получить от яндекса(((
Так на js я формирую json

Javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
    var JsonData = {
      'common': {
      'version': '1.0',
      'api_key': 'ABM6WU0BAAAANfFuIQIAV1pUEYIBeogyUNvVbhNaJPWeM-AAAAAAAAAAAACRXgDsaYNpZWpBczn4Lq6QmkwK6g=='
   },
   'gsm_cells': [
       {
          'countrycode': 250,
          'operatorid': 99,
          'cellid': 42332,
          'lac': 36002,
          'signal_strength': -80,
          'age': 5555
       }
   ],
   'wifi_networks': [
       {
          'mac': '00-1C-F0-E4-BB-F5',
          'signal_strength': -88,
          'age': 0,
       }
   ],
   'ip': {
     'address_v4': '178.247.233.32'
   }
  };

А так отправляю к себе на сервер:

Javascript
1
2
3
4
5
6
$.ajax({
                           type: 'POST',               
                           url: 'test.php',        
                           data: 'checks='+JSON.stringify(JsonData),
                           success:function(result1){ $('#resAjax').append(result1); }
                        });

на сервере проверяю на то что json и в случае успеха делаю следующее:

PHP
1
2
3
4
5
6
7
8
9
$ch = curl_init($url);                                                                     
   curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json"));
   curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");                                                                     
   curl_setopt($ch, CURLOPT_POSTFIELDS, $date1);                                                                  
   curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);                                                                      
    $result = curl_exec($ch);
    curl_close($curl);
    $tokenInfo = json_decode($result, true);
    echo var_dump($result);

Что в результате дает мне сообщение от яндекса
«Specify xml or json param»
ПЛИЗ ПОМОГИТЕ! А то отчислят(((( Где я не прав, как это провернуть чтоб хотя бы ошибку от яндекса получить. А то что сейчас означает что яндекс впринципе не понимает что я ему даю(

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



51 / 17 / 6

Регистрация: 18.05.2007

Сообщений: 1,322

22.04.2016, 14:20

2

Забейте в поисковик вашу ошибку «Specify xml or json param» и прочитайте ответ.
Очевидно что вы просто не указали формат, который вам нужен.



0



0 / 0 / 2

Регистрация: 15.01.2015

Сообщений: 46

22.04.2016, 14:34

 [ТС]

3

я перекопал уже весь инет. Я не нашел решения своей проблемы. Разумеется я написал не все свои попытки в этом сообщении. Суть моей проблемы в том что я потратил уже 18 часа и не решил эту мелкую проблему. Вот просто застопорился и все. Гугл мне не помог, яндекс не помог. Если вам не сложно пожалуйста скажите какую строчку когда мне добавить чтобы получить нужный мне формат.
вот ссылка на документацию от яндекса, мне она особо не помогла( https://tech.yandex.ru/locator… n-docpage/



0



51 / 17 / 6

Регистрация: 18.05.2007

Сообщений: 1,322

22.04.2016, 15:51

4

Просто укажите Яндексу в каком формате вы ожидаете от него ответ. И где код, которым вы отправляете запрос Яндексу? В ваших листингах нет упоминания адреса Яндекса.



0



Geri4

0 / 0 / 2

Регистрация: 15.01.2015

Сообщений: 46

22.04.2016, 20:26

 [ТС]

5

урл вот такой

PHP
1
$url = 'http://api.lbs.yandex.net/geolocation';

Последнее что пытался, подставлять значения как было указано на сайта яндекса в документации о формате отправки запроста json

PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
$myHeader = array( 
"POST: /geolocation HTTP/1.1",
"Host: api.lbs.yandex.net",
"Accept-Encoding: identity",
"Content-length: 742",
"Content-type: application/x-www-form-urlencoded"
 
); 
 
$myHeader = array( 
"POST: /geolocation HTTP/1.1",
"Host: api.lbs.yandex.net",
"Accept-Encoding: identity",
"Content-length: 742",
"Content-type: application/x-www-form-urlencoded"
 
);

а далее пытался сделать следующее

PHP
1
2
3
4
5
6
7
8
$ch = curl_init($url); 
   curl_setopt($ch, CURLOPT_HTTPHEADER, $myHeader);
   curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");                                                                     
   curl_setopt($ch, CURLOPT_POSTFIELDS, $date1);                                                                  
   curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);                                                                      
    $result = curl_exec($ch);
    curl_close($curl);
    $tokenInfo = json_decode($result, true);

Что я не так делаю? Я пробывал и подставлять и ‘Content-type: application/json’ и ‘format: json’ и что только не пробывал. Подскажите пожалуйста. Ткните носом. Ведь то что вы говорите, видимо это я и не понимаю, в этом и есть мой ступор. Видимо я что то просто не так понимаю, и я рад бы узнать как это есть на самом деле, ибо я про это читал, я это знаю, но как показывает практика не понимаю.



0



Geri4

0 / 0 / 2

Регистрация: 15.01.2015

Сообщений: 46

25.04.2016, 05:38

 [ТС]

6

короч все было очень просто=) Проблему решил) Там все по тупому)

PHP
1
2
3
4
5
6
7
8
9
10
$date1=$_POST["checks"];
   $date1= "json={$date1}";
   $ch = curl_init($url);                                                                     
   curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json',' format : json'));  
   curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");                                                                     
   curl_setopt($ch, CURLOPT_POSTFIELDS, $date1);                                                                  
   curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);                                                                      
   $result = curl_exec($ch);
  curl_close($curl);
    $Info = json_decode($result, true);



0



automationName not specified

[info] �[35m[HTTP]�[39m �[37m-->�[39m �[37mPOST�[39m �[37m/wd/hub/session/2140e673-5c20-4a81-8864-6f2d3a8de988/element�[39m
[info] �[35m[HTTP]�[39m �[90m{"using":"id","value":"idp_Name"}�[39m
[debug] �[35m[W3C (2140e673)]�[39m Calling AppiumDriver.findElement() with args: ["id","idp_Name","2140e673-5c20-4a81-8864-6f2d3a8de988"]
[debug] �[35m[BaseDriver]�[39m Valid locator strategies for this request: xpath, id, class name, accessibility id, -android uiautomator
[debug] �[35m[BaseDriver]�[39m Waiting up to 0 ms for condition
[debug] �[35m[AndroidBootstrap]�[39m Sending command to android: {"cmd":"action","action":"find","params":{"strategy":"id","selector":"idp_Name","context":"","multiple":false}}
[debug] �[35m[AndroidBootstrap]�[39m [BOOTSTRAP LOG] [debug] Got data from client: {"cmd":"action","action":"find","params":{"strategy":"id","selector":"idp_Name","context":"","multiple":false}}
[debug] �[35m[AndroidBootstrap]�[39m [BOOTSTRAP LOG] [debug] Got command of type ACTION
[debug] �[35m[AndroidBootstrap]�[39m [BOOTSTRAP LOG] [debug] Got command action: find
[debug] �[35m[AndroidBootstrap]�[39m [BOOTSTRAP LOG] [debug] Finding 'idp_Name' using 'ID' with the contextId: '' multiple: false
[debug] �[35m[AndroidBootstrap]�[39m [BOOTSTRAP LOG] [debug] Using: UiSelector[INSTANCE=0, RESOURCE_ID=com.esri.navigator.qa:id/idp_Name][debug] �[35m[AndroidBootstrap]�[39m [BOOTSTRAP LOG] [debug] Using: UiSelector[INSTANCE=0, RESOURCE_ID=idp_Name]
[debug] �[35m[AndroidBootstrap]�[39m Received command result from bootstrap
[debug] �[35m[W3C (2140e673)]�[39m Responding to client with driver.findElement() result: {"element-6066-11e4-a52e-4f735466cecf":"16","ELEMENT":"16"}
[info] �[35m[HTTP]�[39m �[37m<-- POST /wd/hub/session/2140e673-5c20-4a81-8864-6f2d3a8de988/element �[39m�[32m200�[39m �[90m144 ms - 69�[39m
[info] �[35m[HTTP]�[39m �[90m�[39m
[debug] �[35m[AndroidBootstrap]�[39m [BOOTSTRAP LOG] [debug] Returning result: {"status":0,"value":{"ELEMENT":"16"}}


automationName = "UiAutomator2"

[info] �[35m[HTTP]�[39m �[37m-->�[39m �[37mPOST�[39m �[37m/wd/hub/session/63a7e37d-00a1-48ec-99cc-cf6b5037ef90/element�[39m
[info] �[35m[HTTP]�[39m �[90m{"using":"id","value":"idp_Name"}�[39m
[debug] �[35m[W3C (63a7e37d)]�[39m Calling AppiumDriver.findElement() with args: ["id","idp_Name","63a7e37d-00a1-48ec-99cc-cf6b5037ef90"]
[debug] �[35m[BaseDriver]�[39m Valid locator strategies for this request: xpath, id, class name, accessibility id, -android uiautomator
[debug] �[35m[BaseDriver]�[39m Waiting up to 0 ms for condition
[debug] �[35m[JSONWP Proxy]�[39m Matched '/element' to command name 'findElement'
[debug] �[35m[JSONWP Proxy]�[39m Proxying [POST /element] to [POST http://localhost:8200/wd/hub/session/68d554dd-b7f0-4b1f-8f20-162d03a8acfb/element] with body: {"strategy":"id","selector":"idp_Name","context":"","multiple":false}[info] �[35m[HTTP]�[39m �[37m-->�[39m �[37mPOST�[39m �[37m/wd/hub/session/63a7e37d-00a1-48ec-99cc-cf6b5037ef90/timeouts�[39m
[info] �[35m[HTTP]�[39m �[90m{"implicit":20000}�[39m
[debug] �[35m[W3C (63a7e37d)]�[39m Calling AppiumDriver.timeouts() with args: [null,null,null,null,20000,"63a7e37d-00a1-48ec-99cc-cf6b5037ef90"]
[debug] �[35m[BaseDriver]�[39m W3C timeout argument: {"implicit":20000}}
[debug] �[35m[BaseDriver]�[39m Set implicit wait to 20000ms
[debug] �[35m[W3C (63a7e37d)]�[39m Responding to client with driver.timeouts() result: null
[info] �[35m[HTTP]�[39m �[37m<-- POST /wd/hub/session/63a7e37d-00a1-48ec-99cc-cf6b5037ef90/timeouts �[39m�[32m200�[39m �[90m1 ms - 14�[39m
[info] �[35m[HTTP]�[39m �[90m�[39m[info] �[35m[HTTP]�[39m �[37m-->�[39m �[37mPOST�[39m �[37m/wd/hub/session/63a7e37d-00a1-48ec-99cc-cf6b5037ef90/timeouts�[39m
[info] �[35m[HTTP]�[39m �[90m{"implicit":0}�[39m
[debug] �[35m[W3C (63a7e37d)]�[39m Calling AppiumDriver.timeouts() with args: [null,null,null,null,0,"63a7e37d-00a1-48ec-99cc-cf6b5037ef90"]
[debug] �[35m[BaseDriver]�[39m W3C timeout argument: {"implicit":0}}
[debug] �[35m[BaseDriver]�[39m Set implicit wait to 0ms
[debug] �[35m[W3C (63a7e37d)]�[39m Responding to client with driver.timeouts() result: null
[info] �[35m[HTTP]�[39m �[37m<-- POST /wd/hub/session/63a7e37d-00a1-48ec-99cc-cf6b5037ef90/timeouts �[39m�[32m200�[39m �[90m3 ms - 14�[39m

These are the general steps on how to do this (i assume you already have installed java and the corresponding environment variables):

1) Download and install Apache Tomcat. Configure Netbeans to identify the Apache Tomcat instance you have extracted/installed.

2) Download jersey jar files and add them to your Web Project from here (link: Jersey JAX-RS 2.0 RI bundle), or use the required dependencies if you are working with maven. Don’t forget to add the project to the Apache Tomcat server.

3) Create a Jersey-based java class inside the source folder of your project. In each restful function you will define what data you will accept, how you will proccess them and what you will send. Here is a very basic example:

@Path("/server")
public class RestServer {

   @POST
   @Consumes(MediaType.TEXT_XML)
   @Produces(MediaType.TEXT_XML)
   public String basicPOSTRequest_XMLResponse(String xmlString) {           
      System.out.println("Received: " + xmlString);
      return doSomethingWithString(xmlString);
   }
}

4) Create an ‘index.html’ file in the webContent folder containing the corresponding ajax calls for your restful functions. (the ones you have created in the jersey class). In each ajax call, you will send and receive your data using jQuery functionality. Here is a basic ajax call example:

function ajaxCall(xmlData) {

$.ajax({
    type: "POST",
    url: _baseURI + "/server",
    contentType: "text/xml",
    data: xmlData,  
    datatype: "text/xml",
    success:
            function (data, textStatus, jqXHR){
                alert(data);
            },
    error: 
            function (jqXHR, textStatus, errorThrown) {
                alert("error");
            }
});
}

Note that ajax is just one way to use your restful functions. For example you could do it with another java (or any other language) program that can send Http calls.

5) Start the tomcat server from eclipse.

6) Use your index.html file by hitting it’s url (usually is something like: ‘http://localhost:8080/-yourProjectName-‘) to check the restful functionality of your project.

The above are just guidelines. If you want more details in any step, tell it to me in order to edit my answer.

  • Remove From My Forums
  • Question

  • I am sending a json string or an xml string to a Com object from a C# windows application.

    The Com object is loaded into a Web Page and fires an event that the web page responds to by calling a function that takes the «XML» or «JSON» and attempts to convert it to a Javascript object like this one:

    var FICommand = {

    Command :
    «None»,
            Accession : «None»,
    UserName :
    «Dave»,
    Password :
    «None»,
    OldAccession :
    «None»,
    Event :
    «None»,
    MainExam :
    «None»,
    ReportGuid :
    «None»,
    associatedExams : [] 
    };

    Unfortunately Calling:

    var obj = $.parseJSON(args); 
    Results in an object error

    And this give me an XML error.

    var json = $.xml2json(args);

Answers

  • It seems that the named pipes left behind some invisible strings

    «u0000»

     that JSON could not handle, once I removed them it all worked fine by using:

    var
    json =
    new
    JavaScriptSerializer().Serialize(GlobalClass.PACSEvent);

    • Marked as answer by

      Friday, November 14, 2014 1:40 PM

    • Edited by
      Peter Viau
      Friday, November 14, 2014 1:40 PM

Понравилась статья? Поделить с друзьями:
  • Error code 7 finale
  • Error code 7 14 loading samples failed
  • Error code 679
  • Error code 666
  • Error code 663