GVKun编程网logo

如何从Java客户端使用JSON Web服务?(java web json)

13

对于如何从Java客户端使用JSONWeb服务?感兴趣的读者,本文将提供您所需要的所有信息,我们将详细讲解javawebjson,并且为您提供关于asp.net–如何使用jquery“jsonp”调用

对于如何从Java客户端使用JSON Web服务?感兴趣的读者,本文将提供您所需要的所有信息,我们将详细讲解java web json,并且为您提供关于asp.net – 如何使用jquery“jsonp”调用外部Web服务?、c# – 任何人都使用带有SSRS的WCF客户端Web服务?、C#.NET客户端使用返回哈希数组的外部PHP SOAP Web服务的问题、HBase0.96.x开发使用(三)-- java客户端使用的宝贵知识。

本文目录一览:

如何从Java客户端使用JSON Web服务?(java web json)

如何从Java客户端使用JSON Web服务?(java web json)

public void doView(RenderRequest renderRequest, RenderResponse renderResponse) throws IOException, PortletException {    Map countryList = new HashMap();    String str = "http://10.10.10.25/TEPortalIntegration/CustomerPortalAppIntegrationService.svc/PaymentSchedule/PEPL/Unit336";    try {        URL url = new URL(str);        URLConnection urlc = url.openConnection();        BufferedReader bfr = new BufferedReader(new InputStreamReader(urlc.getInputStream()));        String line, title, des;        while ((line = bfr.readLine()) != null) {            JSONArray jsa = new JSONArray(line);            for (int i = 0; i < jsa.length(); i++) {                JSONObject jo = (JSONObject) jsa.get(i);                title = jo.getString("Amount");                countryList.put(i, title);            }            renderRequest.setAttribute("out-string", countryList);            super.doView(renderRequest, renderResponse);        }    } catch (Exception e) {    }}

我试图json从liferay portlet类访问对象,并且想将任何json字段的值数组传递给jsp页面。

答案1

小编典典

您需要先读取完整的响应,然后才能将其转换为JSON数组。这是因为响应中的每一行都将是一个(无效的)JSON片段,无法单独对其进行解析。稍作修改,您的代码就可以正常工作,重点如下:

// fully read responsefinal String line;final StringBuilder builder = new StringBuilder(2048);while ((line = bfr.readLine()) != null) {    builder.append(line);}// convert response to JSON arrayfinal JSONArray jsa = new JSONArray(builder.toString());// extract out data of interestfor (int i = 0; i < jsa.length(); i++) {    final JSONObject jo = (JSONObject) jsa.get(i);    final String title = jo.getString("Amount");    countryList.put(i, title);}

asp.net – 如何使用jquery“jsonp”调用外部Web服务?

asp.net – 如何使用jquery“jsonp”调用外部Web服务?

我之前有一个问题 can jquery ajax call external webservice?

一些优秀的开发人员回答我使用jsonp,但我不知道如何使用它,我试图使用此代码调用我的服务:

$.ajax({
            type: "POST",url: "http://localhost:1096/MySite/WebService.asmx?callback=?",data: "{}",contentType: "application/json; charset=utf-8",dataType: "jsonp",success: function(msg) {alert(msg);}
            });

这是我的服务代码:

[WebMethod]
public string HelloWorld() {
    return "Hello World " ;
}

任何人都有例子或可以为我解释这个问题?

更新:
我再次编写代码是这样的:

$.getJSON("http://localhost:1096/YourShoppingTest1/WebService.asmx/HelloWorld?jsonp=?",{name:"test"},function(data){
    alert(data.x);
    });

和这样的服务:

[WebMethod]
public string HelloWorld(string name)
{
    return "( {\"x\":10,\"y\":100} )";
}

但它总是在回来时给我这个错误:“丢失;在声明之前
[打破此错误]({“x”:10,“y”:100})“

并且从不调用成功函数,任何人都可以帮忙吗?

解决方法

我有一个类似的问题,不幸的是我没有手头的代码.

从记忆里:

>将[ScriptService]作为属性添加到Web方法中
>还要更改您的网址以调用HelloWorld过程.
像http://localhost:1096/MySite/WebService.asmx/HelloWorld?callback这样的东西

见:What are some good examples of JQuery using JSONP talking to .net?& What is the best way to call a .net webservice using jquery?

c# – 任何人都使用带有SSRS的WCF客户端Web服务?

c# – 任何人都使用带有SSRS的WCF客户端Web服务?

我在使用带有SSRS报告asmx服务的WcfTestClient时遇到问题.有没有人让它上班?
The HTTP request is unauthorized with client authentication scheme 'Anonymous'. The authentication header received from the server was 'Negotiate,NTLM'.

Server stack trace: 
   at System.ServiceModel.Channels.HttpChannelUtilities.ValidateAuthentication(HttpWebRequest request,HttpWebResponse response,WebException responseException,HttpChannelFactory factory)
   at System.ServiceModel.Channels.HttpChannelUtilities.ValidateRequestReplyResponse(HttpWebRequest request,HttpChannelFactory factory,ChannelBinding channelBinding)
   at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
   at System.ServiceModel.Channels.RequestChannel.Request(Message message,TimeSpan timeout)
   at System.ServiceModel.dispatcher.RequestChannelBinder.Request(Message message,TimeSpan timeout)
   at System.ServiceModel.Channels.ServiceChannel.Call(String action,Boolean oneway,ProxyOperationRuntime operation,Object[] ins,Object[] outs,Object[] outs)
   at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall,ProxyOperationRuntime operation)
   at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)

Exception rethrown at [0]: 
   at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg,IMessage retMsg)
   at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData,Int32 type)
   at ReportingService2005Soap.ListSubscriptions(ListSubscriptionsRequest request)
   at ReportingService2005SoapClient.ReportingService2005Soap.ListSubscriptions(ListSubscriptionsRequest request)

解决方法

我在另一篇文章的帮助下想出来了,我现在找不到了.

我使用svcutil实用程序来创建服务/数据协定并提供客户端.然后按如下方式设置绑定.

<basicHttpBinding>
      <binding name="SsRSSoapBinding" >
         <security mode="TransportCredentialOnly">
            <transport clientCredentialType="Ntlm" proxyCredentialType="Ntlm" realm=""/>
            <message clientCredentialType="UserName" algorithmSuite="Default" />
         </security>
      </binding>
    </basicHttpBinding>

C#.NET客户端使用返回哈希数组的外部PHP SOAP Web服务的问题

C#.NET客户端使用返回哈希数组的外部PHP SOAP Web服务的问题

我正在编写一个需要调用外部Web服务的.NET Web应用程序.我提供的文档包括PHP中的代码示例.

我可以使用提供给我的WSDL地址在VS2010中成功创建Web引用,并且使用fiddler我可以看到预期的XML正在发送和接收.但是,.NET似乎在解析返回的XML时遇到问题.

我正在处理的最简单的Web服务只接受一个用户名数组,并且意味着返回一些嵌套的用户哈希数组(每个用户拥有自己的数组名,类型等字段)和一组错误(对于任何用户名)那不匹配).我在’PHP-ish’中描述的文档:

array (
  'users' => array (
    array(
      'id' => 11,
      'username' => 'mick',
      'firstname' => 'Mick',
      'lastname' => 'Byrne'
    ),
    ...
  )
  'errors' => array(
    array(
      'username' => 'whoever',
      'errorcode' => 'NOSUCHUSER'
    )
  )
)

我正在获得与此对应的SOAP XML.但是,当.NET尝试将其转换为结果时,它会抛出异常:

无法将System.Xml.XmlNode []类型的对象分配给System.String类型的对象.

有趣的是,.NET基于WSDL为我创建的相应方法表明它返回一个普通的旧字符串,表明它无法处理WSDL定义返回类型的方式.

完整的WSDL可在此处获得:

http://www.elearning.psychology.org.au/webservice/soap/server.php?wsdl=1&wstoken=dc45858adb6f28b7feae87014d46d9b3

以下是此基本Get Usernames请求中已发送和返回的XML的示例:

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:tns="http://www.elearning.psychology.org.au/webservice/soap/server.PHP?wstoken=dc45858adb6f28b7feae87014d46d9b3" xmlns:types="http://www.elearning.psychology.org.au/webservice/soap/server.PHP?wstoken=dc45858adb6f28b7feae87014d46d9b3/encodedTypes" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <soap:Body soap:encoding>
        <tns:netspot_user_get_users_by_username>
            <usernames href="#id1" />
        </tns:netspot_user_get_users_by_username>
        <soapenc:Array id="id1" soapenc:arrayType="xsd:string[1]">
            <Item>557788</Item>
        </soapenc:Array>
    </soap:Body>
</soap:Envelope>

并回应:

<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://www.elearning.psychology.org.au/webservice/soap/server.PHP?wstoken=dc45858adb6f28b7feae87014d46d9b3" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ns2="http://xml.apache.org/xml-soap" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" SOAP-ENV:encoding>
    <SOAP-ENV:Body>
        <ns1:netspot_user_get_users_by_usernameResponse>
            <return xsi:type="ns2:Map">
                <item>
                    <key xsi:type="xsd:string">errors</key>
                    <value SOAP-ENC:arrayType="ns2:Map[1]" xsi:type="SOAP-ENC:Array">
                        <item xsi:type="ns2:Map">
                            <item>
                                <key xsi:type="xsd:string">username</key>
                                <value xsi:type="xsd:string">557788</value>
                            </item>
                            <item>
                                <key xsi:type="xsd:string">errorcode</key>
                                <value xsi:type="xsd:string">NOSUCHUSER</value>
                            </item>
                        </item>
                    </value>
                </item>
            </return>
        </ns1:netspot_user_get_users_by_usernameResponse>
    </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

任何帮助将不胜感激.

解决方法:

这可能有所帮助:

http://social.msdn.microsoft.com/Forums/en/asmxandxml/thread/f550e2b2-af9e-4653-a618-cffffdc70fdf

http://bytes.com/topic/net/answers/426522-system-invalidcastexception-cannot-assign-object-type-system-xml-xmlnode-object-type-system-string

HBase0.96.x开发使用(三)-- java客户端使用

HBase0.96.x开发使用(三)-- java客户端使用

1、 创建maven项目,将下面配置加入pom.xml

<dependencies>
<dependency>
            <artifactId>slf4j-log4j12</artifactId>
            <groupId>org.slf4j</groupId>
            <version>1.7.5</version>
        </dependency>
        <dependency>
            <groupId>org.hbase</groupId>
            <artifactId>asynchbase</artifactId>
            <version>1.4.1</version>
            <exclusions>
                <exclusion>
                    <artifactId>log4j-over-slf4j</artifactId>
                    <groupId>org.slf4j</groupId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>commons-configuration</groupId>
            <artifactId>commons-configuration</artifactId>
            <version>1.8</version>
        </dependency>
        <dependency>
            <groupId>commons-lang</groupId>
            <artifactId>commons-lang</artifactId>
            <version>2.6</version>
        </dependency>
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.1.3</version>
        </dependency>
        <dependency>
            <groupId>org.apache.hadoop</groupId>
            <artifactId>hadoop-core</artifactId>
            <version>1.2.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.hbase</groupId>
            <artifactId>hbase-common</artifactId>
            <version>0.96.0-hadoop1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.hbase</groupId>
            <artifactId>hbase-client</artifactId>
            <version>0.96.0-hadoop1</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.5</version>
        </dependency>
        <dependency>
            <groupId>org.apache.zookeeper</groupId>
            <artifactId>zookeeper</artifactId>
            <version>3.4.5</version>
            <exclusions>
                <exclusion>
                    <artifactId>slf4j-log4j12</artifactId>
                    <groupId>org.slf4j</groupId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

2、 创建hbase-site.xml文件,添加以下内容:

<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>
<configuration>
<property>
    <name>hbase.zookeeper.quorum</name>
    <value>hadoop234</value>
</property>
</configuration>

注意:本地需要配置host访问hadoop234

3、Java测试代码:

package hbase;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.NavigableMap;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.CellUtil;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HRegionInfo;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.MasterNotRunningException;
import org.apache.hadoop.hbase.ServerName;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.ZooKeeperConnectionException;
import org.apache.hadoop.hbase.client.Delete;
import org.apache.hadoop.hbase.client.Get;
import org.apache.hadoop.hbase.client.HBaseAdmin;
import org.apache.hadoop.hbase.client.HConnection;
import org.apache.hadoop.hbase.client.HConnectionManager;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.client.Increment;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.filter.BinaryComparator;
import org.apache.hadoop.hbase.filter.CompareFilter.CompareOp;
import org.apache.hadoop.hbase.filter.Filter;
import org.apache.hadoop.hbase.filter.RowFilter;
import org.apache.hadoop.hbase.util.Bytes;

/**
 * 
 * 
 * @author whatlly
 */
public class HBaseTest {

	private static Configuration conf = null;

	/**
	 * 初始化配置
	 */
	static {
		conf = HBaseConfiguration.create();
	}
	
	public static void main(String[] args) throws Exception {
		
	}	

	/**
	 * 创建表操作
	 * 
	 * @throws IOException
	 */
	public void createTable(String tablename, String[] cfs) throws IOException {
		HBaseAdmin admin = new HBaseAdmin(conf);
		if (admin.tableExists(tablename)) {
			System.out.println("表已经存在!");
		} else {
			HTableDescriptor tableDesc = new HTableDescriptor(TableName.valueOf(tablename));
			for (int i = 0; i < cfs.length; i++) {
				tableDesc.addFamily(new HColumnDescriptor(cfs[i]));
			}
			admin.createTable(tableDesc);
			admin.close();
			System.out.println("表创建成功!");
		}
	}

	/**
	 * 删除表操作
	 * 
	 * @param tablename
	 * @throws IOException
	 */
	public void deleteTable(String tablename) throws IOException {
		try {
			HBaseAdmin admin = new HBaseAdmin(conf);
			if (admin.tableExists(tablename)) {
				admin.disableTable(tablename);
				admin.deleteTable(tablename);
				System.out.println("表删除成功!");
			} else {
				System.out.println("表不存在");
			}
			admin.close();
		} catch (MasterNotRunningException e) {
			e.printStackTrace();
		} catch (ZooKeeperConnectionException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 插入一行记录
	 * 
	 * @param tablename
	 * @param cfs
	 */
	public void writeRow(String tablename, String[] cfs) {
		try {			
			HTable table = new HTable(conf, tablename);
			Put put = new Put(Bytes.toBytes("row1"));
			for (int j = 0; j < cfs.length; j++) {
				put.add(Bytes.toBytes(cfs[j]), Bytes.toBytes(String.valueOf(1)), Bytes.toBytes("value_1"));
				table.put(put);
			}
			table.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 删除一行记录
	 * 
	 * @param tablename
	 * @param rowkey
	 * @throws IOException
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public void deleteRow(String tablename, String rowkey) throws IOException {
		HTable table = new HTable(conf, tablename);
		List list = new ArrayList();
		Delete d1 = new Delete(rowkey.getBytes());
		list.add(d1);
		table.delete(list);
		table.close();
		System.out.println("删除行成功!");
	}

	/**
	 * 查找一行记录
	 * 
	 * @param tablename
	 * @param rowkey
	 */
	public void selectRow(String tablename, String rowKey) throws IOException {
		HTable table = new HTable(conf, tablename);
		Get g = new Get(Bytes.toBytes(rowKey));
		Result rs = table.get(g);
		System.out.println(rs);
		table.close();
	}

	/**
	 * 查询表中所有行
	 * 
	 * @param tablename
	 */
	public void scaner(String tablename) {
		try {
			HTable table = new HTable(conf, tablename);
			Scan s = new Scan();
			ResultScanner rs = table.getScanner(s);
			for (Result r : rs) {
				System.out.println(r);
			}
			table.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

原文出处: my.oschina.net/u/158197/blog/189272 (原创文章,转载请注明出处)

今天关于如何从Java客户端使用JSON Web服务?java web json的分享就到这里,希望大家有所收获,若想了解更多关于asp.net – 如何使用jquery“jsonp”调用外部Web服务?、c# – 任何人都使用带有SSRS的WCF客户端Web服务?、C#.NET客户端使用返回哈希数组的外部PHP SOAP Web服务的问题、HBase0.96.x开发使用(三)-- java客户端使用等相关知识,可以在本站进行查询。

本文标签: