2016-05-12 69 views
1

我試圖從java發出一個POST請求到一個現有的RESTful服務,以獲得json響應並將其存儲在一個字符串中。如何向Java提供json RESTful服務的發佈請求?

讓我們假設RESTful服務鏈接如下:

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) 

我不知道爲什麼我收到此異常,但如果你有一個想法,或者你也面臨着同樣的問題,我將不勝感激,如果你張貼提示離子或答案。

+1

是您的網絡電纜插入? – Lee

+0

什麼在'at com.stavros.restfulServices.Requester.getJsonRespondingResults(Requester.java:70)'?這是造成異常的原因。提供的代碼包含名稱略有不同的方法。 – sanastasiadis

+0

「UnknownHostException」能否訪問您正在嘗試發佈的網址 – AnupamBhusari

回答

0

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

不存在;請檢查該網址。

+0

我其實沒有給你真實的URL,這就是爲什麼我寫了「讓我們假設RESTful服務網址是」。我用小提琴嘗試了實際的Url,我得到了應有的答案。我想對Java代碼有一些幫助。 RESTful服務有效。我只需要調用它並獲得響應。 – Origamer7

0

這個例外意味着你的主機是未知的。請確保您的網址存在。

java.net.UnknownHostException: myStore.com 
+0

我其實並沒有給你真實的URL,這就是爲什麼我寫了「讓我們假設RESTful服務網址是」。我用小提琴嘗試了實際的Url,我得到了應有的答案。我想對Java代碼有一些幫助。 RESTful服務有效。我只需要調用它並獲得響應。 – Origamer7

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> 

意味着你需要重新驗證web服務的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(); 

    } 
} 
+0

幹得好,我想這個帖子包含了答案。當試圖發送一個請求到'http:// mystore.com'時,他們的web服務器試圖將你重定向到'http:// www.mystore.com'。因此,要解決您的問題,請在您正在使用的網址中添加「www」部分。 – sanastasiadis

+0

我其實沒有給你真實的URL,這就是爲什麼我寫了「讓我們假設RESTful服務網址是」。我用小提琴嘗試了實際的Url,我得到了應有的答案。我想對Java代碼有一些幫助。 RESTful服務有效。我只需要調用它並獲得響應。 – Origamer7

+1

@StavrosVrakas您是否在提琴手中打開了「關注重定向」選項?請嘗試關閉,並報告結果。 – sanastasiadis

0

請看看here,然後提供一個默認HostNameVerifier像:

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

reference here

然後,你需要撥打:

HttpsURLConnection.setDefaultHostnameVerifier(new DummyHostnameVerifier()); 
相關問題