Java 调用restful webservice & jackson

package com.bullshit.webcrawler.client.impl;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;

import com.bullshit.storage.entity.AuthUser;
import com.bullshit.storage.entity.Proxy;
import com.bullshit.storage.entity.vo.AuthUsersVo;
import com.fasterxml.jackson.databind.ObjectMapper;

public class ProxyCollectionRestService {

	private static final String targetURL = "http://localhost:8080/blueberry/rest/v1/api/proxies";

	public Proxy[] getAllProxies(){

		Proxy[] proxies = null;
		try {
	          URL restServiceURL = new URL(targetURL);
	          HttpURLConnection httpConnection = (HttpURLConnection) restServiceURL.openConnection();
	          httpConnection.setRequestMethod("GET");
		      httpConnection.setRequestProperty("Accept", "application/json");
		      if (httpConnection.getResponseCode() != 200) {
		             throw new RuntimeException("HTTP GET Request Failed with Error code : "
		                           + httpConnection.getResponseCode());
		      }
		      BufferedReader responseBuffer = new BufferedReader(new InputStreamReader(
		             (httpConnection.getInputStream())));

		      String output;
	          ObjectMapper objectMapper = new ObjectMapper();
	          while ((output = responseBuffer.readLine()) != null) {
	        	  proxies = objectMapper.readValue(output, Proxy[].class);
	        	  List<Proxy> myObjects22 = objectMapper.readValue(output, objectMapper.getTypeFactory().constructCollectionType(List.class, Proxy.class));
	              System.out.println(myObjects22.size());
	        	  break;
	          }
	          httpConnection.disconnect();
	     } catch (MalformedURLException e) {
	          e.printStackTrace();
	     } catch (IOException e) {
	          e.printStackTrace();
	     }
		return proxies;
	}

	public AuthUsersVo postAuthUserInfo(AuthUser record){

		AuthUsersVo authUsersVo = null;
		 try {

             URL targetUrl = new URL(targetURL);

             HttpURLConnection httpConnection = (HttpURLConnection) targetUrl.openConnection();
             httpConnection.setDoOutput(true);
             httpConnection.setRequestMethod("POST");
             httpConnection.setRequestProperty("Content-Type", "application/json");

             ObjectMapper objectMapper = new ObjectMapper();
             String input = objectMapper.writeValueAsString(record);

             OutputStream outputStream = httpConnection.getOutputStream();
             outputStream.write(input.getBytes());
             outputStream.flush();

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

             BufferedReader responseBuffer = new BufferedReader(new InputStreamReader(
                           (httpConnection.getInputStream())));

             String output;
             System.out.println("Output from Server:\n");
             while ((output = responseBuffer.readLine()) != null) {
                    System.out.println(output);
             }

             httpConnection.disconnect();

        } catch (MalformedURLException e) {

             e.printStackTrace();

        } catch (IOException e) {

             e.printStackTrace();

       }
		return authUsersVo;
	}

	public static void main(String[] args) {
		ProxyCollectionRestService service = new ProxyCollectionRestService();

		Proxy[] s = service.getAllProxies();

		System.out.println(s.length);
	}

}

  

时间: 2024-10-10 20:41:22

Java 调用restful webservice & jackson的相关文章

java调用restful webservice(转)

一般来说,大家只会用到GET和POST方法来调用. GET方法的话,参数可以写在url里面. 比如说server的interface用的是@RequestParam或者@PathVariable,在客户端调用的时候,都可以直接写在URL里,具体写法我就不写了,和下面差不多. POST方法.这个有点不一样,参数要写在request 的body里面,而不是URL里面. URL = url = new URL(http://test.webservice.api/test); HttpURLConne

分享一个Android和java调用RESTful Web服务的利器Resting

分享一个Android和java调用RESTful Web服务的利器Resting 当我们调用Web服务,往往是最终目标是取HTTP响应,将其转化为将在应用中呈现的值对象.Resting可以用来实现这一功能.Resting,在Java的一个轻量级的REST框架,可用于调用一个RESTful Web服务,并转换成响应来自客户端应用程序定制的Java对象.由于它的简单,resting是适合Android等手持设备. resting目标?暴露简单的get(),post(),put()和delete()

Java调用doNet webService方法

doNet的webService 浏览器访问测试地址:http://192.168.4.17/JLWWS/sendCommand.asmx,出现 点击getDeviceValue方法,出现 上图的xml代码再贴一遍: POST /JLWWS/sendCommand.asmx HTTP/1.1 Host: 192.168.4.17 Content-Type: text/xml; charset=utf-8 Content-Length: length SOAPAction: "http://tem

JAVA调用.NET WebService终极方案(包含对SoapHeader的处理)

一.前言: 今日部门的产品需要用到短信功能,需要走公司统一的接口,而该短信接口是由.net开发的,利用两天时间彻底搞定了用java来调用.net 的web service,包括对soap header的处理. 二.解决方案 查询了下java中对soap的支持,有几种方案,有axis和xfire等,我这里先选择的是axis的1.4版本,随即开始开发,这里面有个大坑啊.就是java对类的属性中的getXXXX方法解析后生成的xml文件的属性首字母是小写的,与.NET的生成的xml对不上,光这个问题耗

java调用CXF WebService接口的两种方式

通过http://localhost:7002/card/services/HelloWorld?wsdl访问到xml如下,说明接口写对了. 2.静态调用 // 创建WebService客户端代理工厂        JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();        // 判断是否抛出异常        factory.getOutInterceptors().add(new LoggingInIntercept

Axis2 java调用.net webservice接口的问题(郑州就维)

[html] view plaincopy 这是一个古老的问题,古老到从我若干年前遇到这样的问题就是一个解决之道:反复尝试.其实标准是什么,标准就是一个束缚,一种按既定规则的束缚,错点点,你的调用就可能不成功,不成功后你要花费大量的力气查找原因和错误,差异很多帖子,查找相似的地方,Webservice的实现不同,Soap,CXF,Axis等,每种工具都有指定的方式,刚开始尝试Soap发现这个根本没合适的包进行调用,也是IBM比较老的jar,2001年写的比较复杂,我对比较复杂的东西向来不感兴趣,

java 调用.net webservice

JAVA代码如下: static void testTextString() { try { String methodSayTo = "test"; // 定义服务 Service service = new Service(); Call call2 = (Call) service.createCall(); call2.setTargetEndpointAddress(new java.net.URL("http://localhost:21972/Service1.

Java调用天气Webservice的小应用

废话不多说,直接贴代码: CityReq.java package com.weather; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(name="getWeatherbyCityName",namespace="http://WebXml.com.cn/") public class Ci

Node.js 调用 restful webservice

如何构建一个restful web service参考原来的文章 http://www.cnblogs.com/ericnie/p/5212748.html 直接用原来的项目编译好像有问题,此处耗费1个半钟头,新建立一个项目就完全OK了 :-( 写一个callrest.js,代码如下: var http = require('http');var equal = require('assert').equal; var username = 'falcon';var password = '';