Mostrando entradas con la etiqueta web services. Mostrar todas las entradas
Mostrando entradas con la etiqueta web services. Mostrar todas las entradas

Internal Server Error 500 al intentar ejecutar un web service

descomentar la siguiente línea del web service:

<System.Web.Script.Services.ScriptService()> _


Llamado a un webservice asmx con AJAX

Código .NET

    Imports System.Web
    Imports System.Web.Services
    Imports System.Web.Services.Protocols
    Imports LibX.X
    Imports System.Web.Script.Services
    Imports System.Web.Script.Serialization

    <WebMethod> _
    <ScriptMethod(ResponseFormat:=ResponseFormat.Json)> _
    Sub ObtenerChoiceListItems2(ByVal cobnamtab As String, ByVal filtro As String)
        Dim js As New JavaScriptSerializer()
        Context.Response.Clear()
        Context.Response.ContentType = "application/json"

        Dim d As String = "{ " +
                               "'datos': { " +
                                   "'items': [{ " +
                                   "        'coddestab': '5', " +
                                   "        'deslartab': 'DESC ITEM 5' " +
                                   "    }, { " +
                                   "         'coddestab': '10', " +
                                   "         'deslartab': 'DESC ITEM 10' " +
                                   "     }, { " +
                                   "         'coddestab': '15', " +
                                   "         'deslartab': 'DESC ITEM 15' " +
                                   "}]" +
                                "}" +
                            "}"

        Context.Response.Write(js.Serialize(d))
    End Sub


Código javascript:

function cargarChoiceList(vNombreCombo, vCobnamtab)
{
jQuery.support.cors = true;

rndAux = '&random=' + Math.floor(Math.random()*9999999999);
jqxhr2 = jQuery.ajax({
 type:"GET",               
 data:{ cobnamtab: vCobnamtab,
filtro:"",
rnd: rndAux},  
 dataType:"json",
 url:"http://" + window.self.location.hostname + "/wsX/Parametros.asmx/ObtenerChoiceListItems2",
 beforeSend:function(){
  
 }
}).fail(function(jqXHR, textStatus){  
alert("Error: " + "Status: "+
 jqXHR.status +" detalle: "+ textStatus +
 " detalle: "+ jqXHR.responseText);
}).success(function(data){  
var v = getJSON(data); 
$("[name=" + vNombreCombo + "]").empty();
for (i=0; i<v.datos.items.length; i++)
{
$("[name=" + vNombreCombo + "]").append($('<option>', { 
value: v.datos.items[i]["coddestab"],
text : v.datos.items[i]["deslartab"]
}));
}
});  
}

function getJSON(data_obj)
{
   if (data_obj.d)
      data_ok = data_obj.d;
   else
      data_ok = data_obj;

   evalJson = eval("var varJSON = " + data_ok + ";"); 

   return varJSON;  
}


Ejemplo de llamado:

cargarChoiceList('WFF-SINO3', 'BANCOS');


Obtener cotizaciones de Mercado Libre con gson

package PaqueteAplicacion;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import com.google.gson.Gson;

public class Aplicacion {

    public static void main(String[] args) throws MalformedURLException, IOException {      
        String uri = "https://api.mercadolibre.com/currency_conversions/search?from=USD&to=UYU";
        URL url = new URL(uri);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
       
        connection.setRequestMethod("GET");
        connection.setRequestProperty("Accept", "application/json");

        if (connection.getResponseCode() != 200) {
throw new RuntimeException("Error : HTTP error code : "
+ connection.getResponseCode());
        }

        BufferedReader br = new BufferedReader(new InputStreamReader(
(connection.getInputStream())));

        String output = br.readLine();                              

        Gson gson = new Gson();
        Cotizacion person = gson.fromJson(output, Cotizacion.class);
         
        System.out.println(person.getRatio());
           
        connection.disconnect();
    }
   
}


package PaqueteAplicacion;

import java.math.BigDecimal;

public class Cotizacion {
    private BigDecimal ratio;
    private String mercado_pago_ratio;

    public BigDecimal getRatio() {
        return ratio;
    }

    public void setRatio(BigDecimal ratio) {
        this.ratio = ratio;
    }

    public String getMercado_pago_ratio() {
        return mercado_pago_ratio;
    }

    public void setMercado_pago_ratio(String mercado_pago_ratio) {
        this.mercado_pago_ratio = mercado_pago_ratio;
    }
}

RESTful web services con NetBeans 7.4

1. Crear un Enterprise Application (File / New Project / Java Web / Web Application)
2. Crear una Web Application (File / New Project / Java EE / Enterprise Application) [elegir como Enterprise Application la creada en el paso 1)
3. Sobre el Web Application, click derecho y New / RESTful Web Services from Patterns...
4. Simple Root Resource
5. Como nombre de package, uy.com.prueba.servicios
6. Ingresar el Path (ej /servicio1)
7. Ingresar el nombre de la clase (ej, PruebaResource)
8. Elegir el mime type (ej, text/plain)
9.  En el metodo que esta debajo del @GET, agregar el codigo
            return "hola";
10. Boton derecho en el web application, y deploy.
11. Ir a un browser y poner
           http://localhost:8080/WebApplication2/webresources/servicio1


Invocar webservice jsonp con ajax y jquery

Este ejemplo utiliza NewtonSoft JSON que se puede bajar de acá: http://james.newtonking.com/json


En web.config del webservice:

<system.web>
    <webServices>
      <protocols>
        <add name="HttpGet"/>
      </protocols>
    </webServices>
</system.web>



Página que invoca al servicio:

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>

    <script src="jquery-1.11.0.min.js" type="text/javascript"></script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
 
    <input id="btn1" type="button" value="ok" />
 
 
    </div>
    </form>

<script>
    $(function() {

           var host = "http://localhost:11245/webservice1/Clientes.asmx/ObtenerClientes";

           $("#btn1").click(function() {
               $.ajax({
                   type: 'GET',
                   url: host,
                   data: { prefix: $("#txtNombreT").val() },
                   dataType: "jsonp",
                   jsonpCallback: "funcion1",
                   crossDomain: true,
                   cache: false,                                    
                   error: function(jqXHR, textStatus, errorThrown) {
                       alert(errorThrown);
                   }
               });
           });

     });



        window.localJsonpCallback = function(json) {
            if (!json.Error) {
                alert(json[0].nombre);
            }
            else {
                alert(json.Message);
            }
        }

    });

       //ojo!! esta funcion debe estar fuera del document.ready!!
       //o sino definirla como window.funcion1 = .... VER EJEMPLO ARRIBA
       function funcion1(data) {
           if (!data.Error) {
               datos = data;            
           }
           else {
               alert(data.Message);
           }
       }

</script>

</body>
</html>


Código del webservice:

Ejemplo de lo que debe retornar:

funcion1([
  {
    "nombre": "Juan",
    "documento": "23-10013"
  },
  {
    "nombre": "Pedro",
    "documento": "23-463"
  },
  {
    "nombre": "Silvia",
    "documento": "23-460"
  },
  {
    "nombre": "Fernanda",
    "documento": "23-10132"
  },
  {
    "nombre": "Ricardo",
    "documento": "2-21539085001"
  }
]);


    Public Class pers
        Public nombre As String
        Public documento As String
    End Class

    <WebMethod()> _
    <ScriptMethod(UseHttpGet:=True, ResponseFormat:=ResponseFormat.Json)> _
    Public Sub ObtenerClientes(ByVal prefix As String, ByVal callback As String)
        'Mantis 25829 - rmeneses

        'Dim personas As New List(Of String)()
        Dim personas As New List(Of pers)()

        Dim odb As New SqlDb
        Dim nombre As String

        odb.AbrirDB()
        odb.BeginTran()

        cifIO.cli.LeerClientesBusquedaIncrementalTodos(odb, prefix)

        Dim s As String = ""

        For i As Integer = 0 To odb.dt.Rows.Count - 1
            nombre = CType(odb.dt.Rows(i).Item(3), String)

            s = "{" & Chr(34) & "nombre" & Chr(34) & ": " & Chr(34) & nombre.Trim() & Chr(34) & ", " & _
                          Chr(34) & "documento" & Chr(34) & ": " & Chr(34) & odb.dt.Rows(i).Item(0) & "-" & odb.dt.Rows(i).Item(1) & "-" & odb.dt.Rows(i).Item(2) & Chr(34) & "}"

            Dim p As pers = New pers()
            p.nombre = nombre.Trim()
            p.documento = odb.dt.Rows(i).Item(0) & "-" & odb.dt.Rows(i).Item(1)

            personas.Add(p)
        Next

        Dim sb As New StringBuilder()
        sb.Append(callback & "(")
        sb.Append(JsonConvert.SerializeObject(personas, Formatting.Indented))
        sb.Append(");")

        odb.CommitTran()
        odb.CerrarDB()

        Context.Response.Clear()
        Context.Response.ContentType = "application/json"
        Context.Response.Write(sb.ToString())
        Context.Response.End()
    End Sub


WebService y JSON con jQuery, con Visual Studio 2008 que corre en Visual Studio 2005

1. Crear un web service con visual studio 2008
2. Luego de comprobar que funciona, crear un WebService vacio en Visual Studio 2005 e incorporar los archivos del paso1 (web.config, .asmx, .vb, etc)

Codigo que funciona en VS2005:

web.config


<?xml version="1.0"?>
<!--
    Note: As an alternative to hand editing this file you can use the
    web admin tool to configure settings for your application. Use
    the Website->Asp.Net Configuration option in Visual Studio.
    A full list of settings and comments can be found in
    machine.config.comments usually located in
    \Windows\Microsoft.Net\Framework\v2.x\Config
-->
<configuration>
<configSections>
<sectionGroup name="system.web.extensions" type="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
<sectionGroup name="scripting" type="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
<section name="scriptResourceHandler" type="System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" allowDefinition="MachineToApplication"/>
<sectionGroup name="webServices" type="System.Web.Configuration.ScriptingWebServicesSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
<section name="jsonSerialization" type="System.Web.Configuration.ScriptingJsonSerializationSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" allowDefinition="Everywhere"/>
<section name="profileService" type="System.Web.Configuration.ScriptingProfileServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" allowDefinition="MachineToApplication"/>
<section name="authenticationService" type="System.Web.Configuration.ScriptingAuthenticationServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" allowDefinition="MachineToApplication"/>
<section name="roleService" type="System.Web.Configuration.ScriptingRoleServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" allowDefinition="MachineToApplication"/>
</sectionGroup>
</sectionGroup>
</sectionGroup>
</configSections>
<appSettings/>
<connectionStrings/>
<system.web>
<!--
            Set compilation debug="true" to insert debugging
            symbols into the compiled page. Because this
            affects performance, set this value to true only
            during development.

            Visual Basic options:
            Set strict="true" to disallow all data type conversions
            where data loss can occur.
            Set explicit="true" to force declaration of all variables.
        -->
<compilation debug="true" strict="false" explicit="true">
<assemblies>
<add assembly="System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
<add assembly="System.Data.DataSetExtensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
<add assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add assembly="System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
</assemblies>
</compilation>
<pages>
<namespaces>
<clear/>
<add namespace="System"/>
<add namespace="System.Collections"/>
<add namespace="System.Collections.Generic"/>
<add namespace="System.Collections.Specialized"/>
<add namespace="System.Configuration"/>
<add namespace="System.Text"/>
<add namespace="System.Text.RegularExpressions"/>
<add namespace="System.Linq"/>
<add namespace="System.Xml.Linq"/>
<add namespace="System.Web"/>
<add namespace="System.Web.Caching"/>
<add namespace="System.Web.SessionState"/>
<add namespace="System.Web.Security"/>
<add namespace="System.Web.Profile"/>
<add namespace="System.Web.UI"/>
<add namespace="System.Web.UI.WebControls"/>
<add namespace="System.Web.UI.WebControls.WebParts"/>
<add namespace="System.Web.UI.HtmlControls"/>
</namespaces>
<controls>
<add tagPrefix="asp" namespace="System.Web.UI" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add tagPrefix="asp" namespace="System.Web.UI.WebControls" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</controls>
</pages>
<!--
            The <authentication> section enables configuration
            of the security authentication mode used by
            ASP.NET to identify an incoming user.
        -->
<authentication mode="Windows"/>
<!--
            The <customErrors> section enables configuration
            of what to do if/when an unhandled error occurs
            during the execution of a request. Specifically,
            it enables developers to configure html error pages
            to be displayed in place of a error stack trace.

        <customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
            <error statusCode="403" redirect="NoAccess.htm" />
            <error statusCode="404" redirect="FileNotFound.htm" />
        </customErrors>
        -->
<httpHandlers>
<remove verb="*" path="*.asmx"/>
<add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" validate="false"/>
</httpHandlers>
<httpModules>
<add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</httpModules>
</system.web>
<system.codedom>
<compilers>
<compiler language="c#;cs;csharp" extension=".cs" warningLevel="4" type="Microsoft.CSharp.CSharpCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<providerOption name="CompilerVersion" value="v3.5"/>
<providerOption name="WarnAsError" value="false"/>
</compiler>
<compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" warningLevel="4" type="Microsoft.VisualBasic.VBCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<providerOption name="CompilerVersion" value="v3.5"/>
<providerOption name="OptionInfer" value="true"/>
<providerOption name="WarnAsError" value="false"/>
</compiler>
</compilers>
</system.codedom>
<!--
        The system.webServer section is required for running ASP.NET AJAX under Internet
        Information Services 7.0.  It is not necessary for previous version of IIS.
    -->
<system.webServer>
<validation validateIntegratedModeConfiguration="false"/>
<modules>
<remove name="ScriptModule"/>
<add name="ScriptModule" preCondition="managedHandler" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</modules>
<handlers>
<remove name="WebServiceHandlerFactory-Integrated"/>
<remove name="ScriptHandlerFactory"/>
<remove name="ScriptHandlerFactoryAppServices"/>
<remove name="ScriptResource"/>
<add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add name="ScriptResource" preCondition="integratedMode" verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</handlers>
</system.webServer>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Extensions" publicKeyToken="31bf3856ad364e35"/>
<bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0"/>
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Extensions.Design" publicKeyToken="31bf3856ad364e35"/>
<bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0"/>
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>


Prueba.asmx


Imports System.Web
Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports LibX.X

' To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
<System.Web.Script.Services.ScriptService()> _
<WebService(Namespace:="http://tempuri.org/")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Public Class Service
    Inherits System.Web.Services.WebService

    <WebMethod()> _
    Public Function Consulta1(param1 As String, param2 As String) As String

        Return "{ 'datos': [ {'nombre': 'Juan', 'direccion': 'Colonia 1212'}, {'nombre': 'Pedro', 'direccion': 'Mercedes 1111'} ] }"

    End Function
End Class

Llamado desde javascript con jquery:

var url_ws
url_ws = "http://" + window.self.location.hostname + "/wsTEST/Prueba.asmx/Consulta1";
jQuery.ajax({
type: "POST",
url: url_ws,
data: "{'param1': '4', 'param2': '10'}",
contentType:"application/json; charset=utf-8",
dataType:"json",
async: false,
cache: false,
success: function(response) {
var v = getJSON(response);
if (v.datos[0].nombre != "")
$("#"+div_display).html("&nbsp;&nbsp" + v.datos[0].nombre);
else
$("#"+div_display).html("Cliente no existe");
},
error: function(xhr, ajaxOptions, thrownError) {
//$("#"+div_display).html("Error al obtener el nombre del cliente");
}
});

         function getJSON(data_obj)
        {
                if (data_obj.d)
                      data_ok = data_obj.d;
               else
                      data_ok = data_obj;

               evalJson = eval("var varJSON = " + data_ok + ";"); 

               return varJSON;  
         }




Llamar a un webmethod de un WebService con jQuery

Versiones:
Visual Studio 2008
jquery-1.4.1.min.js
System.Web.Extensions.dll versión 3.5.0.0

Código C#

using System;
using System.Web.Services;

namespace wsX
{
    /// <summary>
    /// Descripción breve de Service1
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]  
    [System.Web.Script.Services.ScriptService]
    public class Service1 : System.Web.Services.WebService
    {
        [WebMethod]
        public string Prueba1(int param)
        {        
            return "{ 'datos': [ {'nombre': 'Juan', 'direccion': 'Colonia 1212'}, {'nombre': 'Pedro', 'direccion': 'Mercedes 1111'} ] }";
        }
    }
}


Código html:


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" language="javascript" src="jquery-1.4.1.min.js"></script>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Prueba 1</title>

<body>

<script type="text/javascript">

$(document).ready(function()
{
jQuery.ajax({
  type: "POST",
  url: "http://localhost:2366/Service1.asmx/Prueba1",
  data: "{'param': '123'}",
  contentType:"application/json; charset=utf-8",
  dataType:"json",
  cache: false,
  success: function(response) {
var v = getJSON(response);

alert("Resultado: " + v.datos[0].nombre);
  }
});

function getJSON(data_obj)
{
if (data_obj.d)
 data_ok = data_obj.d;
else
data_ok = data_obj;

evalJson = eval("var varJSON = " + data_ok + ";");

return varJSON;
}
});

</script>

</body>
</html>