Web Services 如何从Java应用程序连接到REST Web服务

68bkxrlz  于 2022-11-15  发布在  Java
关注(0)|答案(3)|浏览(372)

我必须测试EPA的数据交换Web服务。由于创建100个帐户、建筑物、能源使用分布等是很困难的。我希望自动化这个过程。我搜索了代码示例来执行一个简单的GET。我找到的最好的一个是http://pic.dhe.ibm.com/infocenter/tivihelp/v10r1/index.jsp?topic=%2Fcom.ibm.taddm.doc_7.2%2FSDKDevGuide%2Ft_cmdbsdk_restapi_java.html。我根据自己的目的修改了这个代码。
1.对于证书,它将在该行引发错误
1.如果没有证书(已注解掉),连接将超时并在getResponseCode()处抛出异常。
我不敢肯定:
1.提交证书的正确方式是什么
1.如果我正确发送了凭据
1.如果我的代码不完整,因此,应用程序无法获得响应代码
1.我应该使用Eclipse EE(带Web工具平台)并创建项目〉Web应用程序,而不是Eclipse Juno(不带WTP)
先谢谢你了。

package Package1;

import java.io.*;
import java.util.*;
import java.lang.StringBuffer;
import java.net.*;
import java.net.HttpURLConnection;
import javax.net.ssl.HttpsURLConnection;

public class Class1 {

    public static void main (String args[]){

        try{            

        // set this property to the location of the cert file
         System.setProperty("javax.net.ssl.trustStore","C:/Documents and Settings/bhattdr/Desktop/-.energystar.gov.der");   

        String username = "yy777PPP";
        String password = "yy777PPP";
        String userpass = "";

        URL url = new URL("https://portfoliomanager.energystar.gov/wstest/account");
//      URLConnection uc = url.openConnection();
        HttpsURLConnection uc = (HttpsURLConnection) url.openConnection();

        userpass = username + ":" + password;
        String basicAuth = "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary(userpass.getBytes());

        System.out.println("sending request...");

        uc.setRequestMethod("GET");
        uc.setAllowUserInteraction(false);
        uc.setDoOutput(true);
        uc.setRequestProperty( "Content-type", "text/xml" );
        uc.setRequestProperty( "Accept", "text/xml" );

        uc.setRequestProperty ("Authorization", basicAuth);

        System.out.println(uc.getRequestProperties());

//        uc.setRequestProperty( "authorization", "Basic " + encode("administrator:collation"));

//        Map headerFields = uc.getHeaderFields();
//        System.out.println("header fields are: " + headerFields);

        int rspCode = uc.getResponseCode();

        if (rspCode == 200) {
            InputStream is = uc.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);

            String nextLine = br.readLine();
            while (nextLine != null) {
                System.out.println(nextLine);
                nextLine = br.readLine();
            }

        }
        }

        catch(IOException e) { 
            e.printStackTrace();
        }

    }
}
k2fxgqgv

k2fxgqgv1#

你不需要自己卷。

xpcnnkqh

xpcnnkqh2#

你使用的DER文件作为你的密钥库,Java Crypto通常不支持它。使用keytool创建一个JKS或其他支持的密钥库,然后引用它。

zysjyyx4

zysjyyx43#

在所有的REST客户端框架中...你试过OpenFeign吗?它是来自NetFlix堆栈的一个组件。易于使用,适合NetFlix的所有其他组件。
给予看:https://github.com/OpenFeign/feign

相关问题