如何在Java中使用REST

时间:2012-10-16 13:48:11

标签: java web-services rest

使用Java工具

wscompile for RPC
wsimport for Document
etc..

我可以使用WSDL生成命中SOAP Web服务所需的存根和类。

但我不知道如何在REST中做同样的事情。 如何获取命中REST Web服务所需的Java类。 无论如何,打击服务的方式是什么?

有人能告诉我这个方法吗?

11 个答案:

答案 0 :(得分:11)

正如其他人所说,您可以使用较低级别的HTTP API执行此操作,也可以使用更高级别的JAXRS API将服务用作JSON。例如:

Client client = ClientBuilder.newClient();
WebTarget target = client.target("http://host:8080/context/rest/method");
JsonArray response = target.request(MediaType.APPLICATION_JSON).get(JsonArray.class);

答案 1 :(得分:11)

  

工作示例试试这个:)

package restclient;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class NetClientGet {
    public static void main(String[] args) {
        try {

            URL url = new URL("http://localhost:3002/RestWebserviceDemo/rest/json/product/dynamicData?size=5");//your url i.e fetch data from .
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setRequestProperty("Accept", "application/json");
            if (conn.getResponseCode() != 200) {
                throw new RuntimeException("Failed : HTTP Error code : "
                        + conn.getResponseCode());
            }
            InputStreamReader in = new InputStreamReader(conn.getInputStream());
            BufferedReader br = new BufferedReader(in);
            String output;
            while ((output = br.readLine()) != null) {
                System.out.println(output);
            }
            conn.disconnect();

        } catch (Exception e) {
            System.out.println("Exception in NetClientGet:- " + e);
        }
    }
}

答案 2 :(得分:2)

只需使用正确的查询字符串或请求正文对所需的网址发出http请求。

例如,您可以使用java.net.HttpURLConnection,然后通过connection.getInputStream()消费,然后将其存储到您的对象中。

春天有一个restTemplate让一切变得容易。

答案 3 :(得分:2)

看看Jersey。同样,REST就是数据。教程here

答案 4 :(得分:2)

如果您还需要转换作为服务调用响应的xml字符串,您需要的x对象可以按如下方式执行:

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

import javax.xml.bind.JAXB;
import javax.xml.bind.JAXBException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.CharacterData;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class RestServiceClient {

// http://localhost:8080/RESTfulExample/json/product/get
public static void main(String[] args) throws ParserConfigurationException,
SAXException {

try {

URL url = new URL(
    "http://localhost:8080/CustomerDB/webresources/co.com.mazf.ciudad");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/xml");

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

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

String output;

Ciudades ciudades = new Ciudades();
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println("12132312");
System.err.println(output);

DocumentBuilder db = DocumentBuilderFactory.newInstance()
    .newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(output));

Document doc = db.parse(is);
NodeList nodes = ((org.w3c.dom.Document) doc)
    .getElementsByTagName("ciudad");

for (int i = 0; i < nodes.getLength(); i++) {
    Ciudad ciudad = new Ciudad();
    Element element = (Element) nodes.item(i);

    NodeList name = element.getElementsByTagName("idCiudad");
    Element element2 = (Element) name.item(0);

    ciudad.setIdCiudad(Integer
        .valueOf(getCharacterDataFromElement(element2)));

    NodeList title = element.getElementsByTagName("nomCiudad");
    element2 = (Element) title.item(0);

    ciudad.setNombre(getCharacterDataFromElement(element2));

    ciudades.getPartnerAccount().add(ciudad);
}
}

for (Ciudad ciudad1 : ciudades.getPartnerAccount()) {
System.out.println(ciudad1.getIdCiudad());
System.out.println(ciudad1.getNombre());
}

conn.disconnect();

} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

public static String getCharacterDataFromElement(Element e) {
Node child = e.getFirstChild();
if (child instanceof CharacterData) {
CharacterData cd = (CharacterData) child;
return cd.getData();
}
return "";
}
}

请注意,我在示例中预期的xml结构如下:

<ciudad><idCiudad>1</idCiudad><nomCiudad>BOGOTA</nomCiudad></ciudad>

答案 5 :(得分:1)

从您的问题不清楚您是否使用任何框架。对于REST,您将获得WADL&amp; Apache CXF最近添加了对WADL首次开发REST服务的支持。请查看http://cxf.apache.org/docs/index.html

答案 6 :(得分:1)

它只是一行代码。

mycoll.aggregate([{'$project':{'itemName':{'$toUpper':'$item'},'itemNo':1}}])

Ref. Spring.io consuming-rest

答案 7 :(得分:0)

JAX-RS但您也可以使用标准Java附带的常规DOM

答案 8 :(得分:0)

您可以使用RestTemplate.class在Spring中使用Restful Web服务。

示例:

public class Application {

    public static void main(String args[]) {
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> call= restTemplate.getForEntity("http://localhost:8080/SpringExample/hello");
        System.out.println(call.getBody())
    }

}

Reference

答案 9 :(得分:0)

Apache Http Client API非常常用于调用HTTP Rest服务。

以下是使用HTTP GET调用的示例之一。

ERROR TypeError: results.map is not a function

如果使用Maven项目,请使用以下maven依赖项。

import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.HttpClientBuilder;

public class CallHTTPGetService {

public static void main(String[] args) throws ClientProtocolException, IOException {


    HttpClient client = HttpClientBuilder.create().build();
    HttpUriRequest httpUriRequest = new HttpGet("URL");

    HttpResponse response = client.execute(httpUriRequest);
    System.out.println(response);

}
}

答案 10 :(得分:0)

下面的代码将有助于通过Java使用rest api。 URL -终点休息 如果您不需要任何身份验证,则无需编写 authStringEnd 变量

该方法将返回一个带有您响应的JsonObject

public JSONObject getAllTypes() throws JSONException, IOException {
        String url = "/api/atlas/types";
        String authString = name + ":" + password;
        String authStringEnc = new BASE64Encoder().encode(authString.getBytes());
        javax.ws.rs.client.Client client = ClientBuilder.newClient();
        WebTarget webTarget = client.target(host + url);
        Invocation.Builder invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON).header("Authorization", "Basic " + authStringEnc);

        Response response = invocationBuilder.get();
        String output = response.readEntity(String.class
        );

        System.out.println(response.toString());
        JSONObject obj = new JSONObject(output);

        return obj;
    }