如何从Java发出json RESTful服务的发布请求?

时间:2016-05-12 09:33:22

标签: java

我正在尝试从java向现有RESTful服务发出POST请求,以获取json响应并将其存储在String中。

我们假设RESTful Service Url如下:

https://myStore.com/REST-API/

这是一种带有产品的商店,您想要搜索商品。为了进行搜索,您还必须发送Request Body

{
   "searchProduct": "Football"
}

为了发布该帖子,我在java中实现了以下方法:

public String getJsonResponse(String searchProduct) throws Exception {

    String url = "https://myStore.com/REST-API/";
    String requestBody = "{\"searchProduct\": \"" + searchProduct + "\"}";

    URL obj = new URL(url);

    HttpsURLConnection connection = (HttpsURLConnection) obj
            .openConnection();

    connection.setDoOutput(true);
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", "application/json");

    OutputStream outputStream = connection.getOutputStream(); // <-- I get an exception.

    outputStream.write(requestBody.getBytes());
    outputStream.flush();

    BufferedReader in = new BufferedReader(new InputStreamReader(
            connection.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();

    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }

    in.close();

    return response.toString();

}

例外情况如下:

Exception in thread "main" java.net.UnknownHostException: myStore.com
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:184)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:589)
at sun.security.ssl.SSLSocketImpl.connect(SSLSocketImpl.java:668)
at sun.security.ssl.BaseSSLSocketImpl.connect(BaseSSLSocketImpl.java:173)
at sun.net.NetworkClient.doConnect(NetworkClient.java:180)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:432)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:527)
at sun.net.www.protocol.https.HttpsClient.<init>(HttpsClient.java:264)
at sun.net.www.protocol.https.HttpsClient.New(HttpsClient.java:367)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.getNewHttpClient(AbstractDelegateHttpsURLConnection.java:191)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect0(HttpURLConnection.java:1105)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:999)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:177)
at sun.net.www.protocol.http.HttpURLConnection.getOutputStream0(HttpURLConnection.java:1283)
at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:1258)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java:250)
at com.stavros.restfulServices.Requester.getJsonRespondingResults(Requester.java:70)
at com.stavros.restfulServices.MyMain.main(MyMain.java:11)

我不知道为什么我会得到这个例外,但是如果你有想法或者你也遇到了同样的问题,如果你发表建议或答案,我将不胜感激。

4 个答案:

答案 0 :(得分:2)

我尝试运行您的代码并收到此错误

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head><title>301 Moved Permanently</title></head>
<body><h1>Moved Permanently</h1>
<p>The document has moved <a href="http://www.myStore.com/REST-API/">here</a>.</p>
<hr><address>Apache/2.4.7 (Ubuntu) Server at mystore.com Port 80</address></body></html>

表示您需要重新验证webservice的url,可能是它被移动到其他主机。 https://en.wikipedia.org/wiki/HTTP_301

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;



public class Test {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
      try {
        System.out.println(getJsonResponse("Football"));
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    }

    public static String getJsonResponse(String searchProduct) throws Exception {

        String url = "https://myStore.com/REST-API/";
        String requestBody = "{\"searchProduct\": \"" + searchProduct + "\"}";

        URL obj = new URL(url);

        HttpsURLConnection connection = (HttpsURLConnection) obj
                .openConnection();

        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");

        OutputStream outputStream = connection.getOutputStream(); // <-- I get an exception.

        outputStream.write(requestBody.getBytes());
        outputStream.flush();

        BufferedReader in = new BufferedReader(new InputStreamReader(
                connection.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }

        in.close();

        return response.toString();

    }
}

答案 1 :(得分:0)

https://myStore.com/REST-API/

不存在;请检查该网址。

答案 2 :(得分:0)

此异常表示您的主机未知。请确保您的网址存在。

java.net.UnknownHostException: myStore.com

答案 3 :(得分:0)

请查看here,然后提供默认HostNameVerifier,如:

public class DummyHostnameVerifier implements HostnameVerifier {
    @Override
    public boolean verify(String s, SSLSession sslSession) {
        return true;
    }
}

reference here

然后你需要打电话:

HttpsURLConnection.setDefaultHostnameVerifier(new DummyHostnameVerifier());