我正在與一些其他API進行集成,我需要調用它們的URL來接收數據。RestApi發送請求到特定的URL
我只是想知道是否有可能使用REST Web服務將映射到該特定的URL而不是本地的,然後我將寫入將映射到這些調用的客戶端。
例如:
@Path("/URL")
public class MessageRestService {
@GET
@Path("/{param}")
public Response printMessage(@PathParam("param") String msg) {
String result = "Restful example : " + msg;
return Response.status(200).entity(result).build();
}
}
我不能讓從例如使用AngularJs客戶端直接API調用,因爲我得到這個錯誤:
Response to preflight request doesn't pass access control check: No 'Access- Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:63342' is therefore not allowed access. The response had HTTP status code 400.
我確實發現代碼樣本直API調用來自java的URL,但它看起來很凌亂,尤其是當您需要爲很多API調用創建它時:
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;
public class Connection {
public static void main(String[] args) {
try {
URL url = new URL("INSERT URL HERE");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
String messageToPost = "POST";
OutputStream os = conn.getOutputStream();
os.write(input.getBytes());
os.flush();
conn.connect();
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
嘿,謝謝你的回答。我會檢查這個,看看它是否有幫助 –