如何使用JAVA中的PUT方法通过HttpsUrlConnection发送数据?

时间:2015-05-28 12:53:15

标签: java web-services rest https

我使用HttpsURLConnection建立了安全连接。我可以成功执行get和post方法,但是当我尝试使用PUT方法使用相同的POST方法代码时,我收到错误代码400.我在google上发现StringEntity用于发送HttpURLConnection的数据但是它HttpsURLConnection不支持。 有人可以指导我如何在HTTPS上执行PUT方法。 关于HTTPS,Google上的支持确实非常少。有没有可能有帮助的博客?

以下是我的代码:

{
    "_id" : "abc.xt",
    "user" : "xt",
    "db" : "abc",
    "credentials" : {
        "SCRAM-SHA-1" : {
            "iterationCount" : 10000,
            "salt" : "mydgFCRFo05wh616qw6g1g==",
            "storedKey" : "c8YfzCZZ1qqw2EM8MRDQugQFk4s=",
            "serverKey" : "4JVLAIevhbJI6PtdDRRbelJa4pU="
        }
    },
    "roles" : [
        {
            "role" : "dbOwner",
            "db" : "abc"
        }
    ]
}

这种方式适用于POST方法,但不适用于PUT。我尝试了其他一些但却无法做到。请帮助。

以下是我的错误日志:

public void methodPut(JSONObject JsonObj) throws Exception
{
    //making the connection object and passing it through the ssl certificate using the simple x509trustmanager class
    String httpsURL = <here goes my HTTPS URL>;
    URL myurl = new URL(httpsURL);
    SSLContext ssl = SSLContext.getInstance("TLSv1");
    ssl.init(null, new TrustManager[]{new SimpleX509TrustManager()}, null);
    SSLSocketFactory factory = ssl.getSocketFactory();
    HttpsURLConnection con = (HttpsURLConnection)myurl.openConnection();
    con.setSSLSocketFactory(factory);

    //preparing the connection for PUT
    con.setDoInput(true);
    con.setDoOutput(true);
    con.setInstanceFollowRedirects( false );
    con.setRequestMethod("PUT");
    con.setRequestProperty( "Content-Type", "application/json"); 
    con.setRequestProperty("Accept", "application/json");
    con.setRequestProperty("X-API-Version", "120");
    con.setUseCaches( false );


    //adding the json data as the parameter

    OutputStreamWriter wr= new OutputStreamWriter(con.getOutputStream());
    wr.write(JsonObj.toString());  //JsonObj contains all the data that needs to be modified
    wr.flush();

    //getting the information from the server

     InputStream ins = con.getInputStream();
     InputStreamReader isr = new InputStreamReader(ins);
     BufferedReader in = new BufferedReader(isr);

     //output the information        

     String inputLine;
     while ((inputLine = in.readLine()) != null)
     {
         System.out.println(inputLine);
     }
     in.close();

}

错误即将出现:

java.io.IOException: Server returned HTTP response code: 400 for URL:<my HTTPS URL>
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(Unknown Source)
at rest.HttpsClient.methodPut(HttpsClient.java:261)
at rest.GetOneViewDetails.main(GetOneViewDetails.java:97)

0 个答案:

没有答案