2017-07-18 51 views
-2

正在嘗試使用JSON Array數據創建JAVA GET Http連接請求,如下所示。其中,作爲相同的代碼與任何參數(?即數據= {..})的作品如何使用JSON Array作爲參數調用JAVA GET請求

String myurl = "https://myserver.com/test/api/v1/parameter?data={"username":{"name":"testusername"},"salary":{"sal":"56748","bonus":"3221"},"category":{"cat":"CATA"}}"; 
String newmyurl = myurl.replaceAll("\"","\\\""); 
     log.info("**newmyurl*** "+newmyurl); 
     URL url = new URL(newmyurl);    
     log.info("**URL*** "+url); 
     HttpURLConnection con = (HttpURLConnection) url.openConnection();    
      // By default it is GET request 
      con.setRequestMethod("GET"); 
      con.setRequestProperty("Accept", "application/json");    
      int responseCode = con.getResponseCode(); // Code breaks here nothing errors in log 
      BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); 
     String output; 
     StringBuffer sb = new StringBuffer();  
     while ((output = in.readLine()) != null) { 
     sb.append(output); 
     } 
     in.close(); 

     //printing result from response 
     log.info("****return string****"+sb.toString()); 
+0

你的代碼是不是有效的Java。請發佈[mcve]並解釋什麼不起作用。訪問[幫助]並閱讀[問]。 –

回答

0

爲了逃避在URL中的字符,使用URLEncoder的:

String myjson = "{\"username\":{\"name\":\"testusername\"},\"salary\":{\"sal\":\"56748\",\"bonus\":\"3221\"},\"category\":{\"cat\":\"CATA\"}}"; 
String myurl = "https://myserver.com/test/api/v1/parameter?data=" + URLEncoder.encode(myjson, "UTF-8");