我正在与一些其他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();
}
}
}
嘿,谢谢你的回答。我会检查这个,看看它是否有帮助 –