1

I am trying to make a POST request from java, to an existing RESTful Service, in order to get the json response and store it in a String.

Let's assume that the RESTful Service Url is the following:

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

which is a kind of store with products and you want to search for an item. In order to make a search you have to send also the Request Body as such:

{
   "searchProduct": "Football"
}

In order to make that post I implemented the following method in 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();

}

The exception is the following:

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)

I do not know why I am getting this exception, but in case you have an idea or you have also faced the same problem, I would appreciate it if you were posting a suggestion or an answer.

Origamer7
  • 315
  • 3
  • 17
  • 1
    Is your network cable plugged in? – Lee May 12 '16 at 09:37
  • What's in `at com.stavros.restfulServices.Requester.getJsonRespondingResults(Requester.java:70)`? This is causing the exception. The provided code includes a method with a slightly different name. – sanastasiadis May 12 '16 at 09:41
  • "UnknownHostException" can you access the url you are trying to Post – AnupamBhusari May 12 '16 at 09:42
  • did you test this request with CURL? – Ivan Zelenskyy May 12 '16 at 09:43
  • is your computer turned on? – ACV May 12 '16 at 10:32
  • 1
    @IvanZelenskyy: I actually did not send you the real URL, that is why i wrote "Let's assume that the RESTful Service Url is". I tried the actual Url with fiddler and I get the response as I supposed to. I would like to have some help with the Java code. The RESTful Service works. I just need to call it and get the response. – Origamer7 May 12 '16 at 11:08
  • @sanastasiadis: You are right, but I have to say that I have copied the exception from the actual method I use. That means that the exception is correct but instead of: at com.stavros.restfulServices.Requester.getJsonRespondingResults(Requester.java:70) there is: at com.stavros.restfulServices.Requester.getJsonResponse(Requester.java:70) My class is called "Requester". – Origamer7 May 12 '16 at 11:11
  • @ACV: Nice question. I appreciate humor :) – Origamer7 May 12 '16 at 11:14
  • @anupambhusari: I actually did not send you the real URL, that is why i wrote "Let's assume that the RESTful Service Url is". I tried the actual Url with fiddler and I get the response as I supposed to. I would like to have some help with the Java code. The RESTful Service works. I just need to call it and get the response. – Origamer7 May 12 '16 at 11:16
  • @StavrosVrakas Do you have "Follow Redirects" option turned on in Fiddler? Please try with turned-off also, and report the results. – sanastasiadis May 12 '16 at 13:09
  • @sanastasiadis: I unchecked "Follow Redirects" in fiddler and there is no difference. I still get the exact same response. – Origamer7 May 12 '16 at 13:23
  • Fine. Did you tried any other HttpClients, like Apache? – Ivan Zelenskyy May 12 '16 at 13:46

4 Answers4

2

i try to run your code and get this error

<!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>

Means you need to revalidate the url of webservice may be it is moved to some other host. 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();

    }
}
Bilal
  • 138
  • 1
  • 8
  • Good job, I guess this post includes the answer. When trying to send a request to `http://mystore.com` their web server is trying to redirect you to `http://www.mystore.com`. So, to resolve your issue add the `www` part also in the url you are using. – sanastasiadis May 12 '16 at 10:44
  • I actually did not send you the real URL, that is why i wrote "Let's assume that the RESTful Service Url is". I tried the actual Url with fiddler and I get the response as I supposed to. I would like to have some help with the Java code. The RESTful Service works. I just need to call it and get the response. – Origamer7 May 12 '16 at 11:21
  • 1
    @StavrosVrakas Do you have "Follow Redirects" option turned on in Fiddler? Please try with turned-off also, and report the results. – sanastasiadis May 12 '16 at 13:03
0

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

doesn't exists; please check that url.

victor sosa
  • 899
  • 13
  • 27
  • I actually did not send you the real URL, that is why i wrote "Let's assume that the RESTful Service Url is". I tried the actual Url with fiddler and I get the response as I supposed to. I would like to have some help with the Java code. The RESTful Service works. I just need to call it and get the response. – Origamer7 May 12 '16 at 11:21
0

This exception means that your host is unknown. Please make sure your url exists.

java.net.UnknownHostException: myStore.com
Chit Khine
  • 830
  • 1
  • 13
  • 34
  • I actually did not send you the real URL, that is why i wrote "Let's assume that the RESTful Service Url is". I tried the actual Url with fiddler and I get the response as I supposed to. I would like to have some help with the Java code. The RESTful Service works. I just need to call it and get the response. – Origamer7 May 12 '16 at 11:21
0

Please have a look here and then provide a default HostNameVerifier like:

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

reference here

Then you need to call:

HttpsURLConnection.setDefaultHostnameVerifier(new DummyHostnameVerifier());
Community
  • 1
  • 1
sanastasiadis
  • 1,182
  • 1
  • 15
  • 23