0

嘗試將python代碼轉換爲java代碼以獲得httppost請求,但始終得到400響應。嘗試在我的電腦中使用與本地Web服務相同的代碼,則不存在任何問題。請參閱Python代碼:得到400響應httpurlconnection發送post請求

post_data = {'monitoredObjects':'VZLab-IViewG10-2','monitoredObjectType':'Probe'} 

print(post_data) 

postfields = urlencode(post_data) 


response = BytesIO() 

b = pycurl.Curl() 

b.setopt(b.URL, base+"capture") 

b.setopt(b.HTTPHEADER, ['username:'+username,'securitytoken:'+securitytoken]) 

b.setopt(b.SSL_VERIFYPEER, 0) 

b.setopt(a.SSL_VERIFYHOST, 0) 

b.setopt(b.WRITEDATA, response) 

b.setopt(b.POST, 1) 

b.setopt(b.POSTFIELDS, postfields) 

b.perform() 

b.close() 

我的Java代碼:

public void method(){ 
    String securityToken = "12134"; 
    HashMap<String, String> header = new HashMap<String, String>(); 

    header.put("username", username); 
    header.put("password", password); 
    header.put("securitytoken", securityToken); 

    String api = "capture"; 

    JsonObject parameters = new JsonObject(); 

    parameters.addProperty("monitoredObjects", System.getProperty("monitoredObjects")); 

    parameters.addProperty("monitoredObjectType", System.getProperty("monitoredObjectType")); 
    String captureResult = executePost(baseUrl, api, header, parameters.toString(), "POST"); 

    String captureid = Xml.getXPathValue(result, "//startCapture/isa:captureId/text()"); 
} 

public static String executePost(String baseUrl, String api, HashMap header, String urlParameters, String httpMethod) { 
    HttpURLConnection connection = null; 
    try { 
     // Create connection 
     URL url = new URL(baseUrl + api); 
     connection = (HttpURLConnection) url.openConnection(); 
     connection.setRequestMethod(httpMethod); 
     connection.setRequestProperty("Content-Type", "application/json"); 

     connection.setRequestProperty("Content-Language", "en-US"); 

     connection.setRequestProperty("username", (String) header.get("username")); 
     connection.setRequestProperty("securitytoken", (String) header.get("securitytoken")); 

     /* 
     * String userPassword = username + ":" + password; String encoding = new 
     * sun.misc.BASE64Encoder().encode(userPassword.getBytes()); connection.setRequestProperty("Authorization", "Basic " + 
     * encoding); 
     */ 

     // connection.setRequestProperty("Accept-Encoding", "gzip"); 

     connection.setUseCaches(false); 
     connection.setDoOutput(true); 

     // Send request 
     if (urlParameters != null) { 
      String encodedString = URLEncoder.encode(urlParameters); 
      OutputStream wr = connection.getOutputStream(); 
      BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(wr, "UTF-8")); 
      writer.write(encodedString); 
      writer.flush(); 
      writer.close(); 
      wr.close(); 

      // wr.write(urlParameters.getBytes("UTF-8")); 
      // wr.close(); 
     } 
     int responseCode = connection.getResponseCode(); 
     logger.info("\nSending 'POST' request to URL : " + url); 
     logger.info("Post headers : " + header); 
     logger.info("Post parameters : " + urlParameters); 
     logger.info("Response Code : " + responseCode); 
     // Get Response 
     if (responseCode == 200) { 
      InputStream is = connection.getInputStream(); 
      BufferedReader rd = new BufferedReader(new InputStreamReader(is)); 
      StringBuilder response = new StringBuilder(); 
      String line; 
      while ((line = rd.readLine()) != null) { 
       response.append(line); 
       response.append('\r'); 
      } 
      rd.close(); 

      logger.info("*** BEGIN ***"); 
      logger.info(response.toString()); 
      logger.info("*** END ***"); 
      return response.toString(); 
     } 
     return null; 
    } catch (Exception e) { 
     logger.error(e.getMessage()); 
     return null; 
    } finally { 
     if (connection != null) { 
      connection.disconnect(); 
     } 
    } 
} 
+0

400 HTTP響應是關於錯誤的請求,因此您的請求結構中可能有錯誤,那麼請您提供更多信息,例如「baseUrl」的值是什麼?如果你不能提供這些信息,你至少可以展示它的結構。 –

回答

0

我可以看到你使用JSON對象的蟒蛇爲您的請求參數和使用urlencode來轉換JSON對象中以及形成url參數。 urlencode要求將Json對象作爲參數,但這對於Java來說是不同的。

URLEncoder.encode方法需要一個String對象作爲參數,那麼你就需要在你的Java代碼創建一個JSON對象,你應該做這樣的事情:

... 
String parameters = "monitoredObjects=VZLab-IViewG10-2&monitoredObjectType=Probe"; 
URLEncoder.encode(parameters); 
... 

現在,我知道你轉換JSON對象爲String對象(parameters.toString()),但它只是做了這樣的事情:

"{monitoredObjects:VZLab-IViewG10-2,monitoredObjectType:Probe}" 

因此,這不是一個很好形成的URL,爲此得到了一個400 HTTP效應初探。

我與你分享URLEncoder類的文檔。

https://docs.oracle.com/javase/7/docs/api/java/net/URLEncoder.html#encode%28java.lang.String%29

我希望這個信息可以幫助你。

祝你好運。

+0

String parameters =「monitoredObjects = VZLab-IViewG10-2&monitoredObjectType = Probe」; 它以這種方式工作。謝謝 –

+0

不客氣,如果你喜歡我的回答,請你批准嗎? –

相關問題