调用需要身份验证的REST服务的Java程序
输出:调用需要身份验证的REST服务的Java程序,java,web-services,rest,authentication,post,Java,Web Services,Rest,Authentication,Post,输出: public class RestClient { public static void main(String[] args) { try { JSONObject jsonObject = new JSONObject(); jsonObject.put("fromSku","NONE" ); jsonObject.put("toSku","ASA5500-ENCR-K8" ); jsonObject.pu
public class RestClient {
public static void main(String[] args) {
try {
JSONObject jsonObject = new JSONObject();
jsonObject.put("fromSku","NONE" );
jsonObject.put("toSku","ASA5500-ENCR-K8" );
jsonObject.put("modelNo", "ASAV10");
jsonObject.put("serialNo", "ASATSTSN");
System.out.println(jsonObject);
URL url = new URL("http://licruleswb- dev.cloudapps.cisco.com/LicenseRules/rest/invokeASARule");
URLConnection connection = url.openConnection();
connection.setDoOutput(true);
String encodedCredentials = new String(
org.apache.commons.codec.binary.Base64.encodeBase64
(org.apache.commons.codec.binary.StringUtils.getBytesUtf8("username:password"))
);
System.out.println(encodedCredentials);
connection.setRequestProperty ("Authorization", encodedCredentials);
connection.setRequestProperty("Content-Type", "application/json");
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
out.write(jsonObject.toString());
out.close();
BufferedReader in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
System.out.println(in.toString());
while (in.readLine() != null) {
System.out.println(in.readLine());
}
System.out.println("\nREST Service Invoked Successfully..");
in.close();
} catch (Exception e) {
System.out.println("\nError while calling REST Service");
System.out.println(e);
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
文档已移动
无效的
已成功调用REST服务。。
有人能帮我解决这个问题吗。如果在上的REST客户端广告中使用此链接,则该链接工作正常,但在这个java程序中,它抛出了一个302错误。我在尝试类似操作时遇到了您的线程。对我来说,通过将“Basic”与
encodedCredentials
变量连接起来,使其成为“Basic EncodedValue”,解决了这个问题。服务器用重定向进行响应。如果您想自己用url.openConnection()
实现它,您必须编写代码来处理它——或者使用类似ApacheHttpClient的东西,这使它变得更容易:顺便说一句:302不是一个错误!好啊我也尝试过使用HttpClient,但也没有进行身份验证,并将401身份验证失败作为响应抛出给我。你能帮我解决这个问题吗。
<html><head>
</head><body>
<p>The document has moved <a href="https://wwwin-sso-nprd.cisco.com/obrareq.cgi?wh%3Dlicruleswbintrtpdev-licensingrules.cloudapps.cisco.com%20wu%3D%2FLicenseRules%2Frest%2FinvokeASARule%20wo%3D2%20rh%3Dhttp%3A%2F%2Flicruleswb-dev.cloudapps.cisco.com%20ru%3D%252FLicenseRules%252Frest%252FinvokeASARule">here</a>.</p>
null
REST Service Invoked Successfully..