2016-10-10 8 views
0

バッファ付きのリーダーライタとストリームメソッドを使用せずにコードを修正しようとしています。誰も私のコードを簡素化する方法を私に示唆することができます。リクエストペイロードを残してapi javaストリームのリーダとライタなしでコードを変更します

私はキュウリでこのコードを実行していて、正常に動作しています。

public String creatProduct() throws Throwable { 
    String payload = "{" 
      + "\"productName\":\"Macroon\"," 
      + "\"productCode\":\"\"," 
      + "\"externalRoomId\":\"\"," 
      + "\"description\":\"\"" 
      + "}"; 

    String requestUrl = "www.example.com"; 
    try { 
     URL url = new URL(requestUrl); 
     HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 
     connection.setDoInput(true); 
     connection.setDoOutput(true); 
     connection.setRequestMethod("POST"); 
     connection.setRequestProperty("Accept", "application/json"); 
     connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); 
     OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); 
     writer.write(payload); 
     writer.close(); 
     BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream())); 
     String line; 
     while ((line = br.readLine()) != null) { 
      jsonString.append(line); 
     } 
     br.close(); 
     connection.disconnect(); 
     System.out.println("Response==>" + jsonString.toString()); 
     Map<String, String> map = new HashMap<String, String>(); 
     ObjectMapper mapper = new ObjectMapper(); 
     System.out.println("Input payload:" + payload); 
     map = mapper.readValue(jsonString.toString(), new TypeReference<HashMap<String, String>>() { 
     }); 
     System.out.println("Output Map: " + map); 
     map.get("productName"); 
     assertEquals("Macroon", map.get("productName")); 
    } catch (Exception e) { 
     throw new RuntimeException(e.getMessage()); 
    } 
    return jsonString.toString(); 
} 

答えて

0

私は自分のコードを変更して動作しています!

HttpClient httpclient = new HttpClient(); 
    PostMethod post = new PostMethod("www.example.com"); 
    post.setRequestEntity(new StringRequestEntity(payload, "application/json", null));  
    httpclient.executeMethod(post); 
    String jsonResponse = post.getResponseBodyAsString(); 
    System.out.println("Response==>"+jsonResponse); 
    Map<String,String> map1 = new HashMap<String,String>(); 
    ObjectMapper mapper=new ObjectMapper(); 
    System.out.println("Input payload:"+ payload); 
    map1 = mapper.readValue(jsonResponse, new TypeReference<HashMap<String, String>>(){}); 
    System.out.println("Output Map: "+map1); 
    map1.get("message"); 
    assertEquals("Success",map1.get("message"));  
関連する問題